0
votes

I would like to take a part of textInput in Shiny to create a variable that will in turn be matched to values in a dataframe (DF) and create textOutput based on that matched value. Say I have an textInput with typical inputs being e.g. ABC 123, ABC 234, ABC 345, BCD 123, BCD 234, BCD 345. I also have a DF that contains one column (Col1) with the 'first' part of a typical textInput i.e. ABC, BCD and another column with a set of corresponding values (Col2) like so

DF <-
   Col1 Col2
1  ABC    W
2  BCD    Y
3  CDE    X
4  DEF    Z

I would like to take textInput, say "ABC 123", select only the 'first' part of it ("ABC") then use this string to find its corresponding value in DF$Col2 and create textOutput in Shiny to populate/output that value, in this case value "W". Similarly, if the user input in textInput (input$UserInput) is CDE 345, I would like the output value to be displayed to be "X".

I can create the 'first' section text and output into relevant space but have trouble with the additional part of using it to find corresponding value in the DF and outputting that instead.

I'm using this to isolate the 'first' part of the text input,

  output$first <- renderText({paste(substr(input$UserInput, 1, 
  nchar(input$UserInput)-4))})  

This outputs the "ABC", "CDE" etc string but I have problems using this for the second step of finding the correct value in DF$Col2 and outputting that instead.

1

1 Answers

1
votes

you can wrap your substr call into a reactive function.

mySelection <- reactive({
    inputString <- paste(substr(input$UserInput, 1, nchar(input$UserInput)-4))
    return(inputString)
})

now the value of inputString will change based on the value of input$UserInput, and can be called anywhere in your script (as mySelection() ).

output$first <- renderText({mySelection()})

you can then extract the value you want with DF[which(DF$col1 == mySelection()),]$col2