Manipulating textInput in R Shiny

Viewed 560

I am relatively new to R and even more new to Shiny (literally first day).

I would like a user to input multiple phrases separated by a comma such as female, aged, diabetes mellitus. I have a dataframe in which one variable, MH2 contains text words. I would like to output a dataframe that contains only the rows in which all of the inputted phrases are present. Sometimes a user may input only one phrase, other times 5.

This is my ui.R

library(shiny)
library(stringr)

# load dataset
load(file = "./data/all_cardiovascular_case_reports.Rdata")

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput(inputId = "phrases", 
                label = "Please enter all the MeSH terms that you would like to search, each separated by a comma:",
                value = ""),

      helpText("Example: female, aged, diabetes mellitus")

    ),
    mainPanel(DT::dataTableOutput("dataframe"))
  )
)

and here is my server.R

library(shiny)

server <- function(input, output)
{
  # where all the code will go
    df <- reactive({

      # counts how many phrases there are
      num_phrases <- str_count(input$phrases, pattern = ", ") + 1

      a <- numeric(num_phrases) # initialize vector to hold all phrases

      # create vector of all entered phrases
      for (i in 1:num_phrases)
      {
        a[i] <- noquote(strsplit(input$phrases, ", ")[[i]][1])
      }

      # make all phrases lowercase
      a <- tolower(a)

      # do exact case match so that each phrase is bound by "\\b"
      a <- paste0("\\b", a, sep = "")
      exact <- "\\b"
      a <- paste0(a, exact, sep = "")

      # subset dataframe over and over again until all phrases used
      for (i in 1:num_phrases)
      {
        final <- final[grepl(pattern = a, x = final$MH2, ignore.case = TRUE), ]
      }

      return(final)
    })

    output$dataframe <- DT::renderDataTable({df()})
}

When I tried running renderText({num_phrases}) I consistently got 1 even when I would input multiple phrases separated by commas. Since then, whenever I try to input multiple phrases, I run into "error: subscript out of bounds." However, when I enter the words separated by a comma only versus a comma and space (entering "female,aged" instead of "female, aged") then that problem disappears, but my dataframe doesn't subset correctly. It can only subset one phrase.

Please advise.

Thanks.

1 Answers
Related