将selectInput存储在字符串/字符对象中

时间:2018-08-27 09:46:59

标签: r shiny shiny-reactivity

我想将变量 input $ var 中的变量存储到一个对象,该对象可以与后者的字符串进行比较。现在,我只是试图通过将其存储到对象 value_stored 在屏幕上打印。但是它不打印任何内容*(错误:无法将类型'closure'强制转换为类型'character'*的向量)。这意味着它没有存储值。

library(shiny)
ui <- fluidPage(
  titlePanel("censusVis"),

  sidebarLayout(
    sidebarPanel(
      helpText("Create demographic maps with 
               information from the 2010 US Census."),

      selectInput("var", 
                  label = "Choose a variable to display",
                  choices = c("Percent White", 
                              "Percent Black",
                              "Percent Hispanic", 
                              "Percent Asian"),
                  selected = "Percent White")
      ),

    mainPanel(
      textOutput("selected_var")
      textOutput("test")
    )
  )
  )

server <- function(input, output) {

  output$selected_var <- renderText({ 
    paste(input$var)
  })

  value_store <- reactive(input$var)

  output$test <- renderText({
   paste(value_store) 
  })

  # I want to use the value in input$var for some comparision. 
  # but value_store unable to store. Help.

}


shinyApp(ui = ui, server = server)

2 个答案:

答案 0 :(得分:1)

我强烈建议使用reactiveValues(用于存储您的无功值的对象)和observeEvent

使用服务器代码:

server <- function(input, output) {
    # Create object for reactive values 
    rv <- reactiveValues(
        value_store = character()
    )
    # When input changes -> update
    observeEvent(input$var, {
        output$selected_var <- renderText({ 
            paste(input$var)
        })
        rv$value_store <- input$var
        output$test <- renderText({
            paste(rv$value_store) 
        })
    })
}

PS:您可以删除paste,因为那里没有任何作用。

答案 1 :(得分:0)

您快要准备好了,您只需要先定义反应性元素,然后在watchEvent()函数中监视输入即可。然后,在观察值内部,您可以使用isolate()更新值。

ui <- fluidPage(
  titlePanel("censusVis"),

  sidebarLayout(
    sidebarPanel(
      helpText("Create demographic maps with 
           information from the 2010 US Census."),

  selectInput("var", 
              label = "Choose a variable to display",
              choices = c("Percent White", 
                          "Percent Black",
                          "Percent Hispanic", 
                          "Percent Asian"),
              selected = "Percent White")
  ),

 mainPanel(
   textOutput("selected_var")
   textOutput("test")
 )
 )
)

server <- function(input, output) {

  value_store <- reactive(val = '')

  observeEvent(input$var, {

    # add to reactive
    isolate(value_store$val = input$var)

    # or render update
    output$selected_var <- renderText({ 
       paste(value_store$val)
     })

  })




 output$test <- renderText({
   paste(value_store$val) 
 })

  # I want to use the value in input$var for some comparision. 
  # but value_store unable to store. Help.

}


shinyApp(ui = ui, server = server)