Pass character vector using textInput


#1

I’m stumped over what I think should be a simple issue. Suppose I have a function, myFunction, that has an argument that is a character vector. Something like:

myFunction <- function(label = NULL){
x <- runif(10)
y <- runif(length(x))
z <- ifelse(x < y, label[1], label[2])
data.frame(x,y,z)
}

and in the R interpreter it yields the following expected result
myFunction(label = c(‘Hello’, ‘Goodbye’))

In shiny, how can I properly use textInput to also pass in a character vector equivalent to

c(‘Hello’, ‘Goodbye’)

Entering those values into the text input box as a string is not giving the expected results in my reproducible code below.

ui <- fluidPage(
textInput(“label”, “Enter Labels”, “”),
verbatimTextOutput(“result”)
)

server <- function(input, output) {
result <- reactive({
myFunction(label = input$label)
})
output$result <- renderPrint({
result()
})
}

shinyApp(ui, server)

Note, I can easily use a selectInput in this example, but those labels are arbitrary and can take anything the user would think of.

Thank you


#2

Shiny doesn’t know how you want to split the string into vector elements. You’ll need to use strsplit yourself: strsplit(input$label, " ")[[1]] for example.


#3

Yup, just tried that based on a similar post I saw on SO. I did it like this

result <- reactive({
labels <- unlist(strsplit(input$label, “,”))
myFunction(label = labels)
})

It works, thank you Joe. However, is that “optimal”. I hate having to recast things. Is there is widget that can intake multiple values in the UI from a textInput like box?