0

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

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)
4

2 回答 2

1

我强烈建议使用reactiveValues(object 来存储您的反应值) 和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,因为它在那里什么都不做。

于 2018-08-27T09:57:42.743 回答
0

你快到了,你只需要先定义反应元素,然后在 observeEvent() 函数中观察输入。然后在观察中使用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)
于 2018-08-27T10:01:30.707 回答