我有一个超过 40 列的数据框。我正在使用 DT::datatable 在 Shiny 应用程序中显示数据框,但由于有很多列,它使应用程序水平增长得太多。我想只显示前 5 列,然后让用户能够显示后面的 5 列,依此类推,就像行一样。这可能吗?
使用
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)
}
)