首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R闪亮:许多呈现*()函数可用的for循环输出

R闪亮:许多呈现*()函数可用的for循环输出
EN

Stack Overflow用户
提问于 2017-10-11 16:46:34
回答 1查看 622关注 0票数 0

我想要做的是使for循环的输出在闪亮的应用程序中对许多呈现输出可用。我创建了一个简单的例子来说明我的问题。每个renderPrint()函数中都有相同的for循环。我是否可以将for循环移到render*()函数之外?

我已经找到了如何在循环中使用reactives的例子,但是还没有找到反向任务的解决方案。谢谢你的帮助和关注。

代码语言:javascript
复制
    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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-11 17:13:50

将for循环提取为函数。只要没有在反应上下文之外调用函数(render*reactiveobserve),就可以在没有问题的函数中使用反应性值。

示例:

代码语言:javascript
复制
printTable <- function() {
  for (i in Table()$rn) {
    print (fun(Table()$a[i], Table()$b[i]))
  }
}

output$summary <- renderPrint({
  printTable()
})

output$data <- renderPrint({
  printTable()
})

或者更有效地,您可以将打印输出捕获为字符串,然后只需重用它:

代码语言:javascript
复制
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()
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46693594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档