Reputation: 482
I have a data frame with more than 40 columns. I am using DT::datatable to show the data frame in a Shiny app, but because of there are many columns it makes the app grow so much horizontally. I would like to show just the first 5 columns and then let the user be able to show the following 5 columns and so on, just like happens with rows. Is this possible?
Upvotes: 2
Views: 1836
Reputation: 7106
Using dataTableProxy()
is possible to modify the table after it is rendered.
Basically what the code is doing is to change the rows that are shown based on action buttons to move forward or go back.
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)
}
)
Upvotes: 3