简体   繁体   中英

How can I store a selectInput in a vector?

I'm trying to save a selectInput in a vector.

In my UI I've got:

selectInput("my_ID", "Search for a name", unique(datatable$names), "Henry")

In my server, I want to save this input in a variable to use it later.

This is basically what I want:

selectedNames <- input$my_ID

Of course, this does not work. So I tried this:

selectedNames <- reactive(input$my_ID)

But I get this warning again:

Error in .getReactiveEnvironment()$currentContext() : Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

I have also tried to do it with an observer and different chunks of code I found on the internet, but nothing worked.

At the end, I want to use the selectedNames is a filter like this:

example <- datatable %>% filter(names %in% selectedNames())

How can I fix this?

Try selectedNames <- reactive({input$my_ID})

Then use selectedNames() in the rest of the app.

See Reactivity - An overview .

Update

Working Test Example:

library(shiny)

datatable <- data.frame(names = c('Henry', 'Charles', 'Robert', 'William'))

ui <- fluidPage(
    selectInput("my_ID", "Search for a name", unique(datatable$names), "Henry")
)

server <- function(input, output, session) {
    selectedNames <- reactive({input$my_ID})

    observeEvent(req(selectedNames()), {
        example <- datatable %>% filter(names %in% selectedNames())
        print(example)
    })
}

shinyApp(ui, server)

You don't really need the reactive and could just use input$my_ID directly, as below:

library(shiny)

datatable <- data.frame(names = c('Henry', 'Charles', 'Robert', 'William'))

ui <- fluidPage(
    selectInput("my_ID", "Search for a name", unique(datatable$names), "Henry")
)

server <- function(input, output, session) {
    observeEvent(req(input$my_ID), {
        example <- datatable %>% filter(names %in% input$my_ID)
        print(example)
    })
}

shinyApp(ui, server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM