【问题标题】:How to aggregate a reactive table in shiny?如何在闪亮中聚合反应表?
【发布时间】:2016-10-03 15:35:11
【问题描述】:

我正在尝试从 Shiny 聚合一个反应表。我的结构类似于this example

library(shiny)

runApp(list(
  ui=pageWithSidebar(headerPanel("Adding entries to table"),
                     sidebarPanel(textInput("text1", "Column 1"),
                                  textInput("text2", "Column 2"),
                                  actionButton("update", "Update Table")),
                     mainPanel(tableOutput("table1"))),
  server=function(input, output, session) {
    values <- reactiveValues()
    values$df <- data.frame(Column1 = NA, Column2 = NA)
    newEntry <- observe({
      if(input$update > 0) {
        newLine <- isolate(c(input$text1, input$text2))
        isolate(values$df <- rbind(values$df, newLine))
      }
    })
    output$table1 <- renderTable({values$df})
  }))

我正在尝试几种方法,例如:

output$table2 <- renderTable({
  as.data.frame(values$Column1, list(values$Column2), sum
})

但是直到现在我还没有得到预期的结果。请问你有什么想法吗?

【问题讨论】:

  • 抱歉这个版本。这是我第一次来这里......
  • 预期的结果是什么?只是添加值?还是添加第二张桌子?
  • 添加第二个包含聚合值的表。例如,如果第 1 列是数字,第 2 列是从 A 到 E 的字母,共有 1000 个条目。然后例如按字母聚合列(函数总和)。
  • 哦,抱歉,我才看到。我的代码有一个错误:Agreggate 没有出现 output$table2

标签: shiny aggregate


【解决方案1】:

您是否在寻找类似行总和的东西?我将apply 函数与sum 一起使用,但是

output$table1 <- renderTable({cbind(values$df, Rowsum = apply(values$df, 1, function(x) sum(as.numeric(x))))})

另外,如果您想删除第一个空行,您可以使用 SO 问题中的建议 linked

看起来像这样:

完整代码:

library(shiny)

runApp(list(
  ui=pageWithSidebar(headerPanel("Adding entries to table"),
                     sidebarPanel(textInput("text1", "Column 1"),
                                  textInput("text2", "Column 2"),
                                  actionButton("update", "Update Table")),
                     mainPanel(tableOutput("table1"))),
  server=function(input, output, session) {
    values <- reactiveValues()
    values$df <- data.frame(Column1 = numeric(0), Column2 = numeric(0))
    newEntry <- observe({
      if(input$update > 0) {
        newLine <- isolate(c(input$text1, input$text2))
        isolate(values$df[nrow(values$df) + 1,] <- c(input$text1, input$text2))
      }
    })
    output$table1 <- renderTable({cbind(values$df, Rowsum = apply(values$df, 1, function(x) sum(as.numeric(x))))})
  }))

请注意,没有实施异常处理。

【讨论】:

  • 谢谢....我的代码有一个错误: output$table2
  • 没问题。查看链接的 stackoverflow 问题中建议的解决方案以删除空行(也在我的代码中实现)。也欢迎来到 Stack Overflow。如果此答案或任何其他答案解决了您的问题,请将其标记为已接受。
  • 是的!那是!收起 NAS。非常感谢你。这是我的代码: output$table2
  • 很高兴它有效。提示:在 cmets 中,您可以使用两个反引号字符来嵌入代码。 (与问题/答案相同)示例:print(x)
猜你喜欢
  • 2018-12-29
  • 1970-01-01
  • 2021-02-16
  • 2017-07-27
  • 1970-01-01
  • 2014-06-07
  • 1970-01-01
  • 2013-07-16
  • 2020-03-05
相关资源
最近更新 更多