Home > Software engineering >  Save user inputs as a character vector in R
Save user inputs as a character vector in R

Time:12-16

Is there a way to store user inputs (textInput) as a character vector to be used later in the program? Say if the user inputs are - FB, AAPL, AMZN, NFLX, GOOGL - I want them to be stored something as

user_inputs <- c("FB", "AAPL", "AMZN", "NFLX", "GOOGL")

Sorry but my code below just errors out. I have trying to get this done for the last 2 hours and any help will be greatly appreciated!

library(shiny)

ui <- fluidPage(
  textInput('vec1', 'Enter a vector (comma delimited)')
  verbatimTextOutput("mytxt")
)

server <- function(input, output) {
  Output$mytxt <- renderPrint{
    for (i in input$vec1){
      i
    } 
  } 
  
    
}

shinyApp(ui, server)

EDIT I want to use it inside shiny.

CodePudding user response:

Just use strsplit on the CSV input:

input <- "FB, AAPL, AMZN, NFLX, GOOGL"
output <- strsplit(input, ",\\s*")[[1]]
output

[1] "FB"    "AAPL"  "AMZN"  "NFLX"  "GOOGL"

CodePudding user response:

Unfortunately, as Tim pointed out you have many errors in your Shiny code, unrelated to splitting a string into a character vector. In particular, you need to separate lines inside fluidPage with commas, output should not be capitalized, and a function like renderPrint should use () and not {}.

Always start with working code as a template before adding your own logic. That makes it much easier to find where your real problem is.

I use Tim's answer to split the string.

library(shiny)

ui <- fluidPage(
    textInput('vec1', 'Enter a vector (comma delimited)'),
    verbatimTextOutput("mytxt")
)

server <- function(input, output) {
    output$mytxt <- renderPrint(strsplit(input$vec1, ",\\s*")[[1]])
}

shinyApp(ui, server)
  • Related