I have an editable datatable which is paginated as follows :
d1 = file.df
output$file.df_data<-DT::renderDataTable(
d1,selection = 'none', editable = list(target = "cell", disable = list(columns = c(which(names(d1) != "product_type")-1))),
rownames = FALSE,
extensions = 'Buttons',
options = list(
paging = TRUE,
searching = TRUE,
fixedColumns = TRUE,
autoWidth = TRUE,
ordering = TRUE,
dom = 'Bfrtip',
buttons = c('csv', 'excel')
),
class = "display"
)
When I make an edit on the current page, move to some other page, and then return to the previous page the edits that I had made on the page disappear. How can I make the edits persist across the pages?
Following is the code I am using to observe edits-
observeEvent(input$file.df_data_cell_edit, {
d1[input$file.df_data_cell_edit$row,input$file.df_data_cell_edit$col+1] <<- input$file.df_data_cell_edit$value
})
You have to use a proxy and the editData function:
library(shiny)
library(DT)
ui <- basicPage(
br(),
DTOutput("dtable")
)
server <- function(input, output, session){
dat <- iris
output[["dtable"]] <- renderDT({
datatable(dat, editable = TRUE)
})
proxy <- dataTableProxy("dtable")
observeEvent(input[["dtable_cell_edit"]], {
info <- input[["dtable_cell_edit"]]
dat <<- editData(dat, info, proxy)
})
}
shinyApp(ui, server)
Related
I want to create a button that downloads the filtered data of a dataTable, so I read these two posts and tried to do like them but I got an error and it didn't show the table rows. (please see the attachment)
R - Download Filtered Datatable
and
Download filtered data from renderDataTable() in Shiny
The error is: 'data' must be 2-dimensional (e.g. data frame or matrix)
This is a part of my code:
#UI SECTION
downloadButton("download_filtered", "Download filtered dataset"),
verbatimTextOutput("filtered_row"),
DT::dataTableOutput("fancyTable"),
tags$hr(),
plotOutput("fancyPlot")
#SERVER SECTION
server <- function(input, output) {
output$fancyTable<- renderDataTable ({
my_data = data_filter()
DT::datatable(my_data, extensions = "Buttons",
options = list(paging = TRUE,
scrollX=TRUE,
searching = TRUE,
ordering = TRUE,
dom = 'l<"sep">Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf'),
pageLength=10,
lengthMenu=c(10,20,50,100) )
)
output$filtered_row <- renderPrint({
input[["fancyTable_rows_all"]]
})
output$download_filtered <- downloadHandler(
filename = "Filtered Data.csv",
content = function(file){
write.csv(my_data[input[["fancyTable_rows_all"]], ],
file)
}
)
})
}
I would be happy if you have any suggestions.
Thank you :)
I have tweaked the code minimally. First I used mtcars instead of my_data.
I think the main issue is to Set server = FALSE in the renderDT function (learned here #Stéphane Laurent) R shiny datatable extension "Buttons" - how to export the whole table to excel?:
library(shiny)
library(DT)
ui <- fluidPage(
downloadButton("download_filtered", "Download filtered dataset"),
verbatimTextOutput("filtered_row"),
DT::dataTableOutput("fancyTable"),
tags$hr(),
plotOutput("fancyPlot")
)
server <- function(input, output, session) {
output$fancyTable <-
DT::renderDT({
datatable(mtcars,
filter = "top",
extensions = "Buttons",
options = list(paging = TRUE,
scrollX=TRUE,
searching = TRUE,
ordering = TRUE,
dom = 'l<"sep">Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf'),
pageLength=10,
lengthMenu=c(10,20,50,100)
)
)
}, server = FALSE
)
output$filtered_row <- renderPrint({
input[["fancyTable_rows_all"]]
})
output$download_filtered <- downloadHandler(
filename = "Filtered Data.csv",
content = function(file){
write.csv(my_data[input[["fancyTable_rows_all"]], ],
file)
}
)
}
shinyApp(ui, server)
I am trying to place a button inside the datatable where if the user wants to reset the sorted column they can hit the button and table gets reset or changed to it's original order. At the moment, when I press the button, it is not triggering any event on click. The event should replace the data in the server part.
I am currently following these posts:
shiny DT datatable - reset filters
https://github.com/rstudio/DT/issues/76
Reset a DT table to the original sort order
However, in the last two posts above, even though they get the job done, the button is not part of the datatable.
Here is my reprex:
library(DT)
library(shiny)
library(shinyjs)
# function placed in the global.R
clearSorting <- function(proxy) {
shinyjs::runjs(paste0("$('#' + document.getElementById('", proxy$id,"').getElementsByTagName('table')[0].id).dataTable().fnSort([]);"))
}
# ui.R
ui <- fluidPage(
DT::DTOutput(outputId = "table"),
shinyjs::useShinyjs()
)
# servcer.R
server <- function(input, output) {
output$table <- renderDT({
DT::datatable(data = iris,
filter = 'top',
extensions = c('Buttons'),
options = list(scrollY = 600,
scrollX = TRUE,
autoWidth = TRUE,
dom = '<"float-left"l><"float-right"f>rt<"row"<"col-sm-4"B><"col-sm-4"i><"col-sm-4"p>>',
buttons = list(
list(
extend = '',
text = 'Reset Table',
action = JS("function() {document.getElementById('reset_sort').click();}")
)
),
scrollCollapse= TRUE,
lengthChange = TRUE,
widthChange= TRUE))
})
observeEvent(input$reset_sort, {
data <- iris
clearSorting(proxy = DT::dataTableProxy(outputId = "table"))
DT::replaceData(proxy = DT::dataTableProxy(outputId = "table"),
data = data,
rownames = FALSE)
})
}
shinyApp(ui = ui, server = server)
Here is a way:
library(DT)
js <- c(
"function(e, dt, node, config){",
" dt.iterator('table', function(s){",
" s.aaSorting.length = 0;",
" s.aiDisplay.sort(function(a,b){",
" return a-b;",
" });",
" s.aiDisplayMaster.sort(function(a,b){",
" return a-b;",
" });",
" }).draw();",
"}"
)
datatable(
iris,
extensions = "Buttons",
options = list(
dom = "Bfrtip",
buttons = list(
list(
extend = "collection",
text = "Reset columns order",
action = JS(js)
)
)
)
)
To use it in Shiny, you may need to set server = FALSE in renderDT:
output$table <- renderDT({
......
}, server = FALSE)
Trying to add in the following information to a datatable in Shiny, and getting errors when using the selectinput:
Error: incorrect number of dimensions
library(DT)
library(readr)
library(jsonlite)
library(data.table)
gumdad <- fromJSON("data/boxes.json")
# Define UI for app ----
ui <- fluidPage(
# App title ----
titlePanel("Box Scores"),
#FILTERS
selectInput("season",
"Season:",
c("All",
unique(as.character(gumdad$season)))),
# Main panel for displaying outputs ----
mainPanel(
# Output: Table----
DT::dataTableOutput('tableone')
)
)
# Define server logic ----
server <- function(input, output) {
output$tableone = renderDataTable({
data <- datatable(gumdad, extensions = 'Buttons', rownames = FALSE, escape = FALSE, selection = 'none',
colnames = c('Season', 'Date', 'Opponent', 'Result', 'UNC', 'Opp', 'OT', 'Location', 'Type','Box Score'),
options = list(buttons = c('copy', 'csv'), paging = FALSE, dom = 'Bfrtip')
)
if (input$season != "All") {
data <- data[data$season == input$season,]
}
return(data)
})
gumdad$box <- sapply(gumdad$box, function(x)
toString(tags$a(href=paste0("https://boxscorexxx.com/", x), "Box Score")))
}
shinyApp(ui = ui, server = server)
How can I used the selectInput while customizing the datatable with the correct dimensions?
In your code, data is not a dataframe, this is a datatable. It's not possible to subset it like this: data[data$season == input$season,]. Subset gumdad instead:
output$tableone = renderDT({
data <- gumdad
if (input$season != "All") {
data <- data[data$season == input$season,]
}
datatable(data, extensions = 'Buttons', rownames = FALSE, escape = FALSE, selection = 'none',
colnames = c('Season', 'Date', 'Opponent', 'Result', 'UNC', 'Opp', 'OT', 'Location', 'Type','Box Score'),
options = list(buttons = c('copy', 'csv'), paging = FALSE, dom = 'Bfrtip')
)
})
Also note that you should use renderDT instead of renderDatatable (or use DT::renderDatatable, which is the same as renderDT).
With the button extension to DT package, is there a way to specify that the buttons download either (1) all the data feeding the datatable, or (2) only the data on the visible page.
Below is the example from the documentation.
datatable(
iris, extensions = 'Buttons', options = list(
dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
)
)
As #divibisan said, one option is to use the server argument of renderDT() to control whether the download button will download only the current or all rows.
That would work well if you want to have one download button. However if you want to have two buttons always appear, where one download the current page and one downloads the full dataset, you can use the following code:
library(shiny)
ui <- fluidPage(
DT::DTOutput("table")
)
server <- function(input, output, session) {
output$table <- DT::renderDT(server = FALSE, {
DT::datatable(
mtcars,
extensions = c("Buttons"),
options = list(
dom = 'Bfrtip',
buttons = list(
list(extend = "csv", text = "Download Current Page", filename = "page",
exportOptions = list(
modifier = list(page = "current")
)
),
list(extend = "csv", text = "Download Full Results", filename = "data",
exportOptions = list(
modifier = list(page = "all")
)
)
)
)
)
})
}
shinyApp(ui, server)
See this answer: Buttons: download button with scroller downloads only few rows
Whether the buttons export all data or only visible data is determined by the server argument in the DT::renderDT function call. If server=FALSE then the buttons will export all data in the table, while if server=TRUE they will only export visible data.
You could set the server argument with a variable to make this a selectable option.
output$table <- DT::renderDT(server = input$download_all, {
DT::datatable( ... )
}
The other option you might want to look at is the exportOptions: modifier: selected option that determines whether to download only selected rows (the default) or all rows. You can read about that option here: https://datatables.net/extensions/buttons/examples/print/select.html
Note that your users might run into performance and memory issues using server=FALSE if your data table is very large.
you are looking for the modifiers: page: selected. here is a working example
ui <- fluidPage(
title = "Examples of DataTables",
sidebarLayout(
mainPanel(
tabsetPanel(
id = 'dataset',
tabPanel("diamonds", DT::dataTableOutput("mytable1"))
)
)
)
)
server <- function(input, output) {
# choose columns to display
diamonds2 = diamonds[sample(nrow(diamonds), 1000), ]
output$mytable1 <- DT::renderDataTable({
DT::datatable(diamonds2,
extensions = 'Buttons',
options = list(
dom = 'Bfrtip',
buttons =
list(
list(
extend = 'csv',
buttons = c('csv'),
exportOptions = list(
modifiers = list(page = "current")
)
))
)
)
})
}
shinyApp(ui, server)
hope this helps!
If you want to include the options to download the current page and the entire dataset as both a csv or an excel file, I've managed to implement this as two separate dropdown buttons with those options, together with the copy and print buttons:
Here is the modified working code:
library(shiny)
ui <- fluidPage(
DT::dataTableOutput("table")
)
server <- function(input, output, session) {
output$table <- DT::renderDataTable(server = FALSE, {
DT::datatable(
mtcars,
extensions = "Buttons",
filter = "top",
selection = "none", #this is to avoid select rows if you click on the rows
rownames = FALSE,
options = list(
scrollX = TRUE,
autoWidth = FALSE,
dom = 'Blrtip', # the important thing is that there is the l to allow for the lengthMenu
# https://stackoverflow.com/questions/52645959/r-datatables-do-not-display-buttons-and-length-menu-simultaneously
buttons = list(
# insert buttons with copy and print
# colvis includes the button to select and view only certain columns in the output table
# from https://rstudio.github.io/DT/extensions.html
I('colvis'), 'copy', 'print',
# code for the first dropdown download button
# this will download only the current page only (depends on the number of rows selected in the lengthMenu)
# using modifier = list(page = "current")
# only the columns visible will be downloaded using the columns:":visible" option from:
# https://stackoverflow.com/questions/72317260/how-to-download-only-the-selected-columns-in-a-dataframe-using-colvis-from-dt-in/72317607#72317607
list(
extend = 'collection',
buttons = list(
list(extend = "csv", filename = "page",exportOptions = list(
columns = ":visible",modifier = list(page = "current"))
),
list(extend = 'excel', filename = "page", title = NULL,
exportOptions = list(columns = ":visible",modifier = list(page = "current")))),
text = 'Download current page'),
# code for the second dropdown download button
# this will download the entire dataset using modifier = list(page = "all")
list(
extend = 'collection',
buttons = list(
list(extend = "csv", filename = "data",exportOptions = list(
columns = ":visible",modifier = list(page = "all"))
),
list(extend = 'excel', filename = "data", title = NULL,
exportOptions = list(columns = ":visible",modifier = list(page = "all")))),
text = 'Download all data')
),
# add the option to display more rows as a length menu
lengthMenu = list(c(10, 30, 50, -1),
c('10', '30', '50', 'All'))
),
class = "display"
)
})
}
shinyApp(ui, server)
The tables displayed through the DataTables interface from DT package appear messy (e.g. disordered elements, strange looking pagination ...) when using reactive values which their input come from the rows selected in the first table. Using R version 3.4.3, and shiny 1.1.0 and DT 0.4 which both are sourced from CRAN.
The minimal code:
library(shiny)
library(DT)
ui <- fluidPage(
DT::dataTableOutput("dt"),
actionButton("go", "Go"),
wellPanel(DT::dataTableOutput("selected"))
)
server <- function(input, output, session) {
output$dt <- DT::renderDataTable({
DT::datatable(
mtcars,
style = 'bootstrap',
filter = 'top',
rownames = FALSE,
extensions = 'Buttons',
selection = list(mode = 'single'),
options = list(
pageLength = 10,
dom = '<"top"ifl>t<"bottom"Bp>',
buttons = c('copy', 'csv', 'excel'),
searchHighlight = TRUE
)
)
})
rv <- reactiveValues(val = FALSE)
observeEvent(input$go, {
rv$val <- input$go
})
observeEvent(input$dt_rows_selected, {
rv$val <- FALSE
})
output$selected <- DT::renderDataTable({
if (rv$val == FALSE)
return()
reactive({
validate(need(input$dt_rows_selected != "", "Select a row."))
mtcars[input$dt_rows_selected, ]
}) -> .mtcars
isolate({
DT::datatable(
.mtcars(),
style = 'bootstrap',
filter = 'top',
rownames = FALSE,
extensions = 'Buttons',
selection = list(mode = 'single'),
options = list(
pageLength = 10,
dom = '<"top"ifl>t<"bottom"Bp>',
buttons = c('copy', 'csv', 'excel'),
searchHighlight = TRUE
)
) -> table
})
table
})
}
shinyApp(ui, server)
It looks decent without the second table:
The issue is caused by the part style = 'bootstrap' which does not work well with return(NULL). Replacing if (rv$val == FALSE) return() with req(rv$val) in the output has solved the problem. Has taken the reference here.