我有一个包含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)
}
)