【问题标题】:R Shiny: The for loop output available for many render*() functionsR Shiny:可用于许多 render*() 函数的 for 循环输出
【发布时间】:2018-03-23 10:42:17
【问题描述】:

我想要做的是让 for 循环运行的输出可用于 Shiny App 中的许多渲染输出。 我创建了我的问题的简单示例。 每个 renderPrint() 函数中都有相同的 for 循环。 我可以这样编码,将 for 循环移到 render*() 函数之外吗?

我找到了如何在循环中使用反应式的示例,但还没有找到解决反向任务的方法。 感谢您的帮助和关注。

    library(shiny)

   ui <- fluidPage(sidebarLayout(
      sidebarPanel(
        numericInput(
          inputId = "seed",
          label = "Set seed:",
          value = 1
        ),
       numericInput(
          inputId = "Number",
          label = "Number:",
          value = 1,
          min = 1,
          step = 1
        )
      ),
      mainPanel(
         verbatimTextOutput("summary"),
         dataTableOutput("table"),
         verbatimTextOutput("data")
      )
    ))


    server <- function(input, output) {
      a <- reactive({
        set.seed(input$seed)
        rnorm(input$Number, 2, 1)
      })

      b <- reactive({
        5 * a()
      })

     rn <- reactive({
       c(1:input$Number)
      })

      fun <- function(x, y) {
        x + y
      }

       Table <- reactive({
        data.frame(rn = rn(),
                   a = a(),
                   b = b())
      })


      output$table <- renderDataTable({
        Table()
       })
      output$summary <- renderPrint({
         for (i in Table()$rn) {
           print (fun(Table()$a[i], Table()$b[i]))
       }
        })


        output$data <- renderPrint({
         for (i in Table()$rn) {
           print (fun(Table()$a[i], Table()$b[i]))
         } 
       })
    }


     shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r for-loop shiny shiny-reactivity


    【解决方案1】:

    将 for 循环提取到一个函数中。您可以毫无问题地在函数中使用响应式值,只要您不在响应式上下文之外调用函数(render*reactiveobserve)。

    例子:

    printTable <- function() {
      for (i in Table()$rn) {
        print (fun(Table()$a[i], Table()$b[i]))
      }
    }
    
    output$summary <- renderPrint({
      printTable()
    })
    
    output$data <- renderPrint({
      printTable()
    })
    

    或者更高效,您可以将打印输出捕获为字符串并重新使用它:

    capturedTableString <- reactive({
      capture.output({
        for (i in Table()$rn) {
          print (fun(Table()$a[i], Table()$b[i]))
        }
      })
    })
    
    printTable <- function() {
      cat(capturedTableString(), sep = "\n")
    }
    
    output$summary <- renderPrint({
      printTable()
    })
    

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 2018-10-05
      • 2017-07-31
      • 1970-01-01
      • 2011-01-31
      • 2017-05-14
      • 2021-07-28
      • 2021-07-19
      • 2016-08-18
      相关资源
      最近更新 更多