【问题标题】:How to create a table in a reactive object in Shiny如何在 Shiny 的反应对象中创建表
【发布时间】:2020-07-31 20:50:48
【问题描述】:

我正在尝试在 Shiny 中初始化反应式 data.frame。我想我快到了,但它并没有像预期的那样工作。

下面是一个非常简单的应用程序,我将仅用于说明目的。本质上,表中的值应该根据滑块输入而改变。虽然他们似乎这样做了,但表输出看起来不像我会在 r 中看起来像 data.frame 表。与正常外观不同,它仅输出一列(标题为“数据”)。

我认为我还没有完全理解 reactive() 对象的工作原理,如果在如何初始化响应式对象中的表方面提供任何帮助,我将不胜感激。谢谢!

library(shiny)

ui <- fluidPage(
  tableOutput("first"),
  sliderInput("num","choose num",1,10,1)
)

server <- function(input, output, session) {

  # t1 = (as.data.frame(forecast %>% filter(Date==Sys.Date()-21) %>% group_by(Resort,Date) %>% summarise(`Powder Total` = sum(Snow))))
  # t1=t1[order(t1$`Powder Total`,decreasing=TRUE),][1:5,]

  # output$first = renderTable({
  #   t1[1,]
  #   })

  test = reactive({
    d1 = as.data.frame(matrix(nrow=2,ncol = 2))
    names(d1)=c("col1","col2")
    d1$col1=input$num
    d1$col2=input$num+1
  })

  output$first=renderTable({
    test()
  })

}

shinyApp(ui, server)

【问题讨论】:

    标签: r dataframe shiny reactive


    【解决方案1】:

    这是因为reactive() 不返回数据帧,而是返回长度为 1 的向量。请改用reactiveValues()

    library(shiny)
    
    ui <- fluidPage(
      tableOutput("first"),
      sliderInput("num","choose num",1,10,1)
    )
    
    server <- function(input, output, session) {
    
      # t1 = (as.data.frame(forecast %>% filter(Date==Sys.Date()-21) %>% group_by(Resort,Date) %>% summarise(`Powder Total` = sum(Snow))))
      # t1=t1[order(t1$`Powder Total`,decreasing=TRUE),][1:5,]
    
      # output$first = renderTable({
      #   t1[1,]
      #   })
    
      tableData = reactiveValues(d1 = as.data.frame(matrix(nrow=2,ncol = 2)))
    
      observeEvent(input$num, {
    
        temp = tableData$d1
        names(temp)=c("col1","col2")
        temp$col1=input$num
        temp$col2=input$num+1
    
        tableData$d1 = temp
    
      })
    
      test = reactive({
        d1 = as.data.frame(matrix(nrow=2,ncol = 2))
        names(d1)=c("col1","col2")
        d1$col1=input$num
        d1$col2=input$num+1
      })
    
      output$first=renderTable({
        tableData$d1
      })
    
      observe({print(test())})        # check console output
      observe({print(tableData$d1)})  # check console output
    
      observe({print(is.data.frame(test()))
               print(is.data.frame(tableData$d1))
    
        })
    }
    
    shinyApp(ui, server)
    

    我添加了一些观察调用,让您了解 test() 不是数据框。

    【讨论】:

    • 效果很好,谢谢!只是为了确保我已经正确理解它,它不起作用的原因是因为 reactive() 最多只能有一个长度为 1 的向量。另一方面,reactiveValues() 可以有无限长度,然后允许它创建一个数据帧(因为所有数据帧都是多个向量)?
    • 没错。数据框是向量列表。
    • 你也可以在reactiveValues()中有多个数据框,就像reactiveValues(df1 = mtcars, df2 = iris)一样
    猜你喜欢
    • 2017-12-30
    • 2018-02-07
    • 2013-06-21
    • 2021-12-14
    • 2021-10-26
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多