【问题标题】:Show just few columns DT::datatable shiny R仅显示几列 DT::datatable 闪亮 R
【发布时间】:2021-09-02 14:54:33
【问题描述】:

我有一个超过 40 列的数据框。我正在使用 DT::datatable 在 Shiny 应用程序中显示数据框,但由于有很多列,它使应用程序水平增长得如此之多。我想只显示前 5 列,然后让用户能够显示以下 5 列,依此类推,就像行一样。这可能吗?

【问题讨论】:

  • options = list(scrollX = TRUE) 传递给renderDT() 有助于水平增长,但所有列仍然存在。
  • 非常感谢,这非常有效。重点是不要横向展开页面,这样就完美了。

标签: r shiny datatable


【解决方案1】:

使用dataTableProxy() 可以在表格呈现后对其进行修改。 基本上,代码所做的是根据操作按钮更改显示的行以向前或向后移动。

library(shiny)
library(DT)
library(tidyverse)


#generate some data
df <- rerun(5,iris) %>% reduce(bind_cols)

shinyApp(
    
    ui = fluidPage(
        actionButton('prev_five', 'Previous Cols'),
        actionButton('next_five', 'Next Cols'),
        DTOutput('tbl')),
    
    
    server = function(input, output) {
        
    cols <- reactiveValues()   
    cols$showing <- 1:5    
        
        #show the next five columns 
        observeEvent(input$next_five, {
            #stop when the last column is displayed
            if(cols$showing[[length(cols$showing)]] < length(df)) {
            hideCols(proxy, cols$showing, reset = FALSE) #hide displayed cols
            cols$showing <- cols$showing + 5
            showCols(proxy, cols$showing, reset = FALSE) #show the next five 
            } 
        })
        
        #similar mechanism but reversed to show the previous cols
        observeEvent(input$prev_five, {
            #stop when the first column is displayed
            if(cols$showing[[1]] > 1) {
                hideCols(proxy, cols$showing, reset = FALSE) #hide displayed cols
                cols$showing <- cols$showing - 5
                showCols(proxy, cols$showing, reset = FALSE) #show previous five
            } 
        })
        
        
        
        
        output$tbl = renderDT(
            df,
            options = list(
                columnDefs = list(list(visible = FALSE, targets = 1:length(df))), #hide all columns
                scrollX = TRUE)  #for when many columns are visible
            )
        
        
        proxy <- dataTableProxy('tbl')
        showCols(proxy, 1:5, reset = FALSE) #show the first five cols (because the colums are now all hidden)
    }
)

【讨论】:

  • 这行得通,这是一个有趣的解决方案,谢谢!
猜你喜欢
  • 2016-01-02
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 2017-03-06
  • 2014-10-02
  • 2016-02-18
  • 2017-11-06
  • 2020-02-03
相关资源
最近更新 更多