Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use testInput create a list, and assign the list names as the same textInput in R shiny?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading