I want to create a list based on users’ input via textInput, and the assign the list names with the same textInput.
For instance, if the user’s input is a, then the list name is a, the element is paste0(a, Sys.Data()).
below is my example. I can create the list, but I don’t know how to assign the list names.
library(shiny)
my_list <- reactiveVal(list())
ui <- fluidPage(
textInput(inputId = "my_input", label = "Enter some text:"),
actionButton(inputId = "add_button", label = "Add"),
verbatimTextOutput(outputId = "my_output")
)
server <- function(input, output, session) {
observeEvent(input$add_button, {
new_item <- isolate(input$my_input)
if (nchar(new_item) > 0) {
my_list(append(my_list(), list(paste0(new_item, Sys.Date()))))
}
})
output$my_output <- renderPrint({
my_list()
})
}
shinyApp(ui = ui, server = server)
>Solution :
You could use setNames like so:
library(shiny)
my_list <- reactiveVal(list())
ui <- fluidPage(
textInput(inputId = "my_input", label = "Enter some text:"),
actionButton(inputId = "add_button", label = "Add"),
verbatimTextOutput(outputId = "my_output")
)
server <- function(input, output, session) {
observeEvent(input$add_button, {
new_item <- isolate(input$my_input)
if (nchar(new_item) > 0) {
my_list(append(my_list(), setNames(list(paste0(new_item, Sys.Date())), new_item)))
}
})
output$my_output <- renderPrint({
my_list()
})
}
shinyApp(ui = ui, server = server)
