【问题标题】:Using reactive variable to change a subset of data using Shiny使用反应变量使用 Shiny 更改数据子集
【发布时间】:2015-06-10 17:09:21
【问题描述】:

我有一个跨越数年的数据集。我闪亮的应用程序旨在让用户一次完成一周,进行一些分析并使用该周的新信息更新数据集。例如时间表。

在普通 R 中,我执行以下代码,其中 update_schedule 是自定义函数:

data[indx:(indx+7)] <- update_data(data[indx:(indx+7)], schedule)

使用闪亮,我正在尝试做类似的事情,但得到错误:

.getReactiveEnvironment()$currentContext() 中的错误: 如果没有活动的反应上下文,则不允许操作。 (你试图做一些只能在反应式表达式或观察者内部完成的事情。)

#ui
shinyUI(pageWithSidebar(
  sidebarPanel(
  actionButton("nextButton", "Process Next Week")
  ),

  mainPanel(
    textOutput('week'),
    plotOutput('myplot')
  )
))


#server
data <<- data.frame(value = rep(1:4, 3:6), open = rep(c(1,1,0), 6))

shinyServer(function(input, output) ({

  week <- reactive({as.numeric(input$nextButton)+1})
  output$week <- renderText({week()})

  #this is the problem line
  data[(week()*7):((week()+1)*7)]$open <<- rep(1,7)

  #but here the sub-setting works for plotting
  output$myplot <- renderPlot({
      p1 <- plot(data$value[(week()*7):((week()+1)*7)], 
       col = as.factor(data$open)[(week()*7):((week()+1)*7)])
      return(p1)
     })

  })
)

有没有办法使用 week() 值来选择要更新的部分数据?此外,实际上我正在尝试一次更新多个变量,而不仅仅是本示例中的“打开”列。

我尝试了以下方法以将我的反应变量保留在反应语句中,但出现错误:

data <<- reactive({data %>%
  mutate(open = replace(open, (week()*7):((week()+1)*7, rep(1,7))})

Error in plot(data()$value[(week() * 7):((week() + 1) * 7)], col = as.factor(data()$open)[(week() *  : 
error in evaluating the argument 'x' in selecting a method for function 'plot': Error in UseMethod("mutate_") : 
no applicable method for 'mutate_' applied to an object of class "reactive"

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您是否阅读并完全理解了闪亮教程的反应式表达式章节? http://shiny.rstudio.com/tutorial/lesson6/

    任何使用响应式表达式(week 是响应式的,因为您使用reactive({}) 定义它必须在响应式上下文中使用,例如另一个reactive() 调用或observerenderXXX。你还应该看看reactiveValues()函数

    【讨论】:

    • 是的,我确实阅读了那一章,并且我理解为什么这种方法不起作用,所以我的问题是在这种情况下使用什么方法来实现该结果。我还尝试使用 maggritr 和 replace 来更改每列的值的子集,但 maggritr 似乎无法使用反应变量。
    猜你喜欢
    • 1970-01-01
    • 2016-10-23
    • 2019-03-27
    • 2021-03-07
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 2015-11-24
    • 2014-04-14
    相关资源
    最近更新 更多