【问题标题】:For loop producing multiple reactive valuesFor 循环产生多个反应值
【发布时间】:2016-10-26 16:03:50
【问题描述】:

我正在尝试使用 for 循环生成多个反应变量 (#12)。变量的初始值由应用程序中的用户输入指示。因此,变量必须是反应性的并且与用户输入相关。在循环中,我想在每次循环运行时简单地添加一个......(有点像计数器)。

应用程序要复杂得多,但我只需要知道如何同时使用 for 循环和反应值。所以上面的例子只是学习语法和结构的简化版

请注意,下面的代码不会运行!我只是将它包含在内,以显示我希望应用程序看起来如何......或者我认为它应该!

非常感谢你们的帮助!!!

ui <- fluidPage(
  numericInput("initial", "Enter the initial value here", value = 0),
  verbatimTextOutput("text1")
  verbatimTextOutput("text2")
)

server <- function(input, output, session) {
  counter <- reactiveValues (
    count1 = input$initial,
    count2 = input$initial
  )

  for (i in 1:10) {
    counter$count1 <- counter$count1 + 1
    counter$count2 <- counter$count2 + 2
  }

  output$text1 <- renderPrint(counter$count1)
  output$text2 <- renderPrint(counter$count2)
}

shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny shiny-server


    【解决方案1】:

    您的 for 循环不会产生多个反应值,它只会更新 counter 中的值。如果您需要在 for 循环中向 counter 添加更多元素,可以使用双方括号 [[]] 运算符来完成。比如:

    for (i in 1:10) {
      counter$[[paste0("count",i)]] <- i
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 2011-10-25
      • 2020-04-18
      • 2018-05-08
      • 2019-07-31
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多