【问题标题】:Don't know how to set reactivity values in Shiny不知道如何在 Shiny 中设置反应性值
【发布时间】:2013-09-19 13:27:38
【问题描述】:

我正在尝试构建一个 Shiny 应用程序,它接受许多参数(实验次数、交叉验证的折叠次数和输入数据文件),然后在后台运行一些 .R 脚本。但我不断收到以下错误:

“在没有激活的反应上下文的情况下不允许操作。(你试图做一些只能从反应函数内部完成的事情。)”

这是我的 ui.R 的代码的 sn-p:

library(shiny)

experiments <- list(
  "1" = 1,
  "3" = 3,
  "5" = 5,
  "10" = 10,
  "50" = 50
)
folds <- list(
  "1" = 1,
  "3" = 3,
  "5" = 5,
  "10" = 10
)

shinyUI(
  pageWithSidebar(
    headerPanel("Classification and Regression Models"),
    sidebarPanel(
      selectInput("experiments_number", "Choose Number of Experiments:",
                  choices = experiments)
      selectInput("folds_number", "Choose Number of Folds:", choices = folds),
      fileInput(
        "file1",
        "Choose a CSV file:",
        accept = c('text/csv', 'text/comma-separated-values', 'text/plain')
      )
    ),

以及我的 server.R 代码的开头:

shinyServer(function(input,output){
    # Server logic goes here.

    experimentsInput <- reactive({
        switch(input$experiments_number,
            "1" = 1,
            "3" = 3,
            "5" = 5,
            "10" = 10,
            "50" = 50)
    })

foldsInput <- reactive({
        switch(input$folds_input,
            "1" = 1,
            "3" = 3,
            "5" = 5,
            "10" = 10)
    })

if (is.null(input$file1$datapath))
                return(NULL)

source("CART.R")

有什么想法吗?

谢谢!

【问题讨论】:

  • 我认为如果没有看到什么是 CART.R.,我们什么也说不出来

标签: r shiny


【解决方案1】:

在您的 CART.R 中,您有 dataset &lt;- input$file1$datapath 这一行

您正在访问 server.R 中的这个输入槽,但它不在错误消息告诉您的“反应性上下文”内。

要克服这个错误,你必须将它包装在一个反应​​函数中。

ds <- reactive({
  dataset <- input$file1$datapath
})

并使用ds() 调用它

更新

根据 OP 的澄清请求。这是一种方法:

在 Server.R 中

source("CART.R") #which does NOT access reactive elements
#common functions go here. (non-reactive ones)

shinyServer(function(input, output) { 
  
  ds <- reactive({
    dataset <- input$file1$datapath
  })
         
  output$rt <- renderText({
    {  ds1 <- ds()
      #now ds1 is available in this function
      Do something with ds1
    }
  })

以下是 Shiny 团队的完整示例。 Example 03_reactivity 加载 Shiny 库后,您可以通过键入 runExample("03_reactivity") 来运行它。

希望对您有所帮助。

【讨论】:

  • 好的,我已经将输入包装到反应函数中。但是我在哪里以及如何调用 ds() - 在 server.R 或 CART.R 中?
  • 反应函数将在 server.R 中的 shinyServer 内部调用。对于初学者,我建议将 CART.R 中的所有内容都带入 server.R。如果你真的需要,你可以稍后使用source
  • 谢谢。你能给我一个例子如何做到这一点,我一直在摆弄它,但无法让它工作。 :( 另外,我真的需要使用 source()...
猜你喜欢
  • 2020-06-24
  • 2018-02-07
  • 2019-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-03
  • 2021-04-21
相关资源
最近更新 更多