【问题标题】:How to update datatable after selecting data source from radio button?从单选按钮选择数据源后如何更新数据表?
【发布时间】:2021-03-15 09:16:42
【问题描述】:

我正在准备一个闪亮的应用程序。我有几个数据框,我在其中存储有关人口的数据,按年细分。因此,例如,table_2017 存储 2017 年的数据,table_2018 存储 2018 年的数据等。

我想在表格中显示所有数据,并允许用户选择他感兴趣的年份。我想我会准备一个单选按钮,这样用户就可以选择他感兴趣的年份。

我尝试在按钮 id 中隐藏源表名,然后将其传递给datatable() 函数,不幸的是,此方法不起作用,因为它未被识别为数据框,我收到消息:

“数据”必须是二维的(例如数据框或矩阵)

因此我的问题是:从按钮单选中选择数据源后如何更新数据表?也许有一些现成的工具可以做到这一点(例如updatemenus for plotly)?

这是一个例子:

library(shiny)
library(DT)

ui <- fluidPage(
    
    radioButtons("years", "Choose year", inline = TRUE,
                 c("2017" = "table_2017",
                   "2018" = "table_2018",
                   "2019" = "table_2019")),
    DT::dataTableOutput("table")
       
)


server <- function(input, output) {
    
    a <- c("Region1","Region2","Region3","Region4")
    b <- c(100, 200, 300, 400)
    table_2017 <- data.frame(a,b)
    names(table_2017) <- c('Name', 'Population')
    
    c <- c("Region1","Region2","Region3","Region4")
    d <- c(500, 600, 700, 800)
    table_2018 <- data.frame(c,d)
    names(table_2018) <- c('Name', 'Population')
    
    e <- c("Region1","Region2","Region3","Region4")
    f <- c(900, 1000, 1100, 1200)
    table_2019 <- data.frame(e,f)
    names(table_2019) <- c('Name', 'Population')

    output$table <- DT::renderDataTable({
        
        data <- input$years
        datatable(data)
                        
        
    })
}


shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny datatable reactable


    【解决方案1】:

    这个其实很简单,加get(data))

    问题是您的单选按钮中的input$years 只是一个字符向量,DT::datatable 无法执行。使用 get(),您可以访问 R 环境并评估数据帧,而不是 datatable 中的字符向量。

    然后你的表格输出是

      output$table <- DT::renderDataTable({
        
        data <- input$years
        datatable(get(data))
        
        
      })
    

    顺便说一句,您应该在闪亮的应用程序之外执行所有静态 R 代码。将数据框移到服务器函数之外或 global.R 文件中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多