【问题标题】:Shiny observer - how to use observer to update global variables?闪亮的观察者 - 如何使用观察者更新全局变量?
【发布时间】:2016-10-26 20:15:23
【问题描述】:

如何使用观察者更新全局变量?

我在开始时有一个空物种:

speciesChoices <- c()

但我想在 ui 上发生更改时向其中添加值,所以它变成:

speciesChoices <- c(
    'PM2.5' = 'particles'
)

有可能吗?

到目前为止我的代码...

ui.r:

speciesOptions <- selectInput(
    inputId = "species",
    label = "Species:",
    choices = c(
        # 'PM2.5' = 'particles',
        # 'Humidity %' = 'humidity'
    )
)

server.r:

speciesChoices <- c() # global variable

# Define server logic required to draw a histogram
shinyServer(function(input, output, session) {

   observe({
        key <- input$streams1

        stream <- fromJSON(paste(server, "/output/stream?public_key=", key, sep=""),flatten=TRUE)
        species <- as.data.frame(stream$species)

        # Set choices of title and code for select input.
        speciesChoices <- setNames(species$code_name, species$public_name)

        updateSelectInput(session, "species", choices = speciesChoices)
    })

})

它只更新 ui 上的输入,而不更新服务器上的 speciesChoices。

有什么想法吗?

【问题讨论】:

    标签: r shiny shiny-server


    【解决方案1】:

    使用类似speciesChoices &lt;&lt;- setNames(input$species$code_name, input$species$public_name) 的东西。您既需要超级赋值运算符&lt;&lt;- 来更改全局变量,又需要使用input$_id_ 来引用在ui 中设置的输入。

    旁注:我不确定您的结局是什么,但请确保您确实想要使用观察者而不是反应者。要了解它们之间的区别,请参阅Joe Cheng's slides from useR2016

    【讨论】:

      猜你喜欢
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 2016-02-20
      • 2023-04-10
      相关资源
      最近更新 更多