简体   繁体   English

如何将 selectInput 存储在向量中?

[英]How can I store a selectInput in a vector?

I'm trying to save a selectInput in a vector.我正在尝试将 selectInput 保存在向量中。

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. .getReactiveEnvironment()$currentContext() 中的错误:在没有活动反应上下文的情况下不允许操作。 (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:最后,我想使用 selectedNames 是这样的过滤器:

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

How can I fix this?我怎样才能解决这个问题?

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

Then use selectedNames() in the rest of the app.然后在应用程序的其余部分使用selectedNames()

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:你真的不需要反应式,可以直接使用input$my_ID ,如下所示:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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