I am using in Shiny Buttons extension to download figures in a Excel-File.
DTa <- data.table(
dataSum()[,1],
format(round((10^-6)*dataSum()[,-1],2),nsmall = 2,decimal.mark=",",big.mark=".")
)
DTa<- DT::datatable( DTa, extensions=c("Buttons"),options = list(paging = FALSE,
searching = FALSE,
dom = 'Bfrtip',
#buttons = c('copy','excel')
buttons = list(
list(
extend = 'excel',
text = "Save ",
title = 'KRB'
), list(
extend = 'copy', title = 'krb'
)
)
),
caption= paste("Stichtag:",
as.character(sub("([0-9]{2})([0-9]{2})([0-9]{4})KRB.csv", "\\1.\\2.\\3",input$date))))
In the first part above, I transform the figures in the German format, i.e., I set , as a decimal separator and . as a thousands separator. In the second part, I call the extensions Buttons of DT.
In Shiny, the figures look as follows:
Problem: After pressing the Save Button in Shiny, all figures with just , and without . have the wrong format.
For example, after saving 34,21 becomes 3.421! But 67.809,97 is correct!
How can I keep the format of the figures during the export or save process?
I don't know if it helps:
When I change into the debug mode and execute the second part DTa<- DT::datatable( DTa, extensions ... I see the following:
As one can see the figures in data are characters!
Is it possible to write a JavaScript function in my server.R to use the language.decimal option? There is an example here, however I cannot use it exactly.
Try this
DTa<- DT::datatable(DTa, extensions=c("Buttons"), options = list(paging = FALSE,
searching = FALSE,
dom = 'Bfrtip',
#buttons = c('copy','excel')
buttons = list(
list(
extend = 'excel',
text = "Save ",
title = 'KRB'
), list(
extend = 'copy', title = 'KRB'
)
)
),
caption= paste("Stichtag:",
as.character(sub("([0-9]{2})([0-9]{2})([0-9]{4})KRB.csv", "\\1.\\2.\\3",input$date)))
) %>% formatCurrency(-1,' ', digits = 2 , interval = 3, mark = ".", dec.mark = ",")
Related
The first column of the datatable consits of names, while the second column uses characters which are a combination of numeric with comma delimiters, and characters for other values, for example, "1,000" , "2,000", "19,000", "Data missing", "Data suppressed". Using type = "num-fmt" I am able to get the datatable to display correctly when I run it as a function by itself, i.e. "1,000", "2,000", "19,000", and when using sort in the Rstudio terminal its ordering is correct, and as such when first displayed in the R shiny app it works. However, when using the sort options in the shiny interface, the ordering no longer works correctly, i.e. "1,000" , "19,000" , "2,000".
My understanding is that I must do the sorting in the server, or use java script, but I don't know how.
ui <- dashboardPage(
box(title = "Industries from selected region",
status = "danger",
solidHeader = TRUE,
DT::dataTableOutput("industry_tbl"),
width = 6)
)
server <- function(input, output, session) {
values <- reactiveValues(direction = "Exports",
year = "2020",
partner_country = "Spain",
industry = "Mining",
home_country = "UK")
output$industry_tbl<- DT::renderDT({
industry_table_server(new_data,
values$year,
values$partner_country,
values$direction,
values$home_country)
})
function:
industry_table_server <- function(dataset,
selected_year,
selected_country,
selected_direction,
selected_region){
this_selection <- dplyr::filter(dataset,
Year == selected_year,
Country == selected_country,
Direction == selected_direction,
`Area name` == selected_region) %>%
select(Industry, value)
DT::datatable(this_selection ,
colnames = c("Industry",
paste0("£millions")),
filter = "none",
rownames = TRUE,
extensions = c('Buttons'),
options = list(
dom = 'Bftip',
buttons = c('copy', 'excel', 'print'),
searchHighlight = TRUE,
searchDelay = 0,
selection = "single",
pageLength = 10, # Shows 10 results
lengthMenu = c(5, 10),
columnDefs = list(list(className = 'dt-right', targets = c(0,2)), list(targets = c(2), type = "num-fmt"))
)
)
} ```
As said in the datatables website, regarding the type option:
Please note that if you are using server-side processing this option has no effect since the ordering and search actions are performed by a server-side script.
So you have to set server = FALSE in renderDT:
output$industry_tbl <- renderDT({
industry_table_server(new_data,
values$year,
values$partner_country,
values$direction,
values$home_country)
}, server = FALSE)
I created a data table in Shiny with the first column editable. I can enter texts but they will disappear after I switch input values and then come back. For example, I entered "testing 001" for the Category of "Male Premium BladeRazor System" and everything seemed fine (see the picture). However, after I switch my Category to another value and then come back to "Male Premium BladeRazor System", the entered text of "testing 001" would be gone. My code is pretty long, and I cut part of it for your reference. Any help will be highly appreciated. Thanks.
Example of text edits
output$tabofrandom <- DT::renderDataTable(
if (is.null(names(tab7data$dat))) {
datatable(tab7data$dat)
}
else {
datatable(isolate(tab7data$dat),
editable = list(target = 'cell', disable = list(columns = c(1,2, 3, 4,5,6,7,8,9))),
rownames = FALSE,
selection = list(mode = "single", target = "row", selected = previousSelection),
extensions = c('Buttons'),
options = list(searching=FALSE,
scrollX=T,
scrollY=277,
#processing=FALSE,
autoWidth = TRUE,
displayStart = previousPage,
dom = 'Blfrtip',
# pageLength = 5,
lengthChange = FALSE,
lengthMenu = list(c(5,10, -1), c("5","10", "All")),
buttons = list(c('pageLength','excel'),list(extend = 'colvis')),
# buttons = c('excel','colvis'),
columnDefs=list(list(targets=c(2,4,5,8),
render = JS("function(data){return data.replace(/;/g,
'<br>');}")),
...
))
) %>%
formatStyle(1:10, 'text-align' = 'left') %>%
formatStyle(1:10, 'vertical-align'='top')
} )
...
observeEvent(input[["tabofrandom_cell_edit"]], {
info <- input[["tabofrandom_cell_edit"]]
info$col=info$col+1
previousSelection <<- input$tabofrandom_rows_selected
previousPage <<- input$tabofrandom_rows_current[1] - 1
tab7data$dat<-isolate(DT::editData(tab7data$dat,info))
})
...
You have to set the server option of renderDataTable to FALSE or to use a proxy:
proxy <- DT::dataTableProxy("tabofrandom")
observeEvent(input[["tabofrandom_cell_edit"]], {
info <- input[["tabofrandom_cell_edit"]]
......
tab7data$dat <- DT::editData(tab7data$dat, info, proxy)
})
You don't have to do info$col + 1 for editData.
please I have the following code to display a datatable:
fluidRow(column(3,
dataTableOutput(outputId="table01", width = '100px')))
and this is how the rendered table is created:
output$table01 <- DT::renderDataTable({
df <- get_mp_data()
if(is.null(df)){
df <- data.frame()
}else{
upcolor = "lightblue"
downcolor = "lightblue"
col_name = "CHG"
df <- datatable(df
, rownames = FALSE
, caption = paste0("Pre/Post Duration")
, filter = 'none'
, options = list(scrollX = F
#, lengthChange = FALSE # this feature hides the "Show Entries" on top of the table, so we won't be able to customize how many entries we can see all together
, pagingType = "numbers" # this hides the Next and Previous buttons --> https://datatables.net/reference/option/pagingType
, autoWidth = T
,pageLength = 5 # this determines how many rows we want to see per page
, info = FALSE # this will hide the "Showing 1 of 2..." at the bottom of the table --> https://stackoverflow.com/questions/51730816/remove-showing-1-to-n-of-n-entries-shiny-dt
,searching = FALSE # this removes the search box -> https://stackoverflow.com/questions/35624413/remove-search-option-but-leave-search-columns-option
,columnDefs = list(list(width = '4', targets = c(3) )
,list(width = '4', targets = c(2) )
) # careful, column counting STARTS FROM 0 !
)) %>%
formatStyle(col_name,
#background = styleColorBar(range(df[, c(col_name)]), 'lightblue'),
background = color_from_middle(df[, c(col_name)] , downcolor, upcolor),
backgroundSize = '98% 88%',
backgroundRepeat = 'no-repeat',
backgroundPosition = 'center')
}
return(df)
})
The problem with this code is that it shows "Show Entries" on the top left hand side of the table that takes a lot of useless space. I would like to only keep the dropdown and hide the text "Show Entries".
I couldn't find anything here # https://datatables.net/reference/option about this.
Notice how I don't want to use "lengthChange = FALSE" since this will also hide the dropdown box that allows to customize how many rows can be displayed all together.
Thank you
You can use this option:
datatable(iris, options = list(
language = list(lengthMenu = "_MENU_")
))
I have been using the R Datatable package to display information for a team a work with and spit out html docs for them to use. We are trying to find a way to add comments for all to see on the data tables, so i made the columns editable however i can't find a way to get this information to everyone. I created a save button that would work however i can only get this to save to the downloads folder of whoever is clicking the button. Is there a way to save this file to a public location?
Or a better way to add comments on the DT.
Here is the code im currently using:
---
title: "Comments Test"
output: html_document
---
#### `r format(Sys.time(), "%B %d, %Y")`
```{r echo=FALSE, warning=FALSE}
library(DT)
df <- data.frame(matrix(rnorm(50), nrow=10))
df$Comments <- ""
datatable(df, extensions = c('FixedHeader',
'ColReorder', 'Buttons'),
options = list(
dom = 'Blfrtip',
buttons = list(list( extend = 'csv',
filename = '//public/comments/comments.csv',
text = 'Save')),
autoWidth = TRUE,
fixedHeader = TRUE,
colReorder = TRUE),
width = "965px", fillContainer = FALSE, escape = FALSE,
rownames = FALSE, autoHideNavigation = FALSE, editable = TRUE)
```
Thank You.
Can you please help me with DT::datatable column formatting? I have for example this table:
DT::datatable(iris,
class = 'row-border stripe hover compact',
rownames = F,
autoHideNavigation = T,
options = list(pageLength = nrow(summary.month),
searching = F,
paging = F,
info = F))
I need to set:
1st column: bold, aligned left
3rd coumn: bold, aligned right
I found, that I should use columns.ClassName, but how to set the class styles in R?
The html output of datatable will be used in R markdown document then.
It has been a while since this question was initially asked, but I just had this same problem. Here is a simpler solution that doesn't require editing the source data or calling JS, but instead uses functions within the DT package itself.
DT::datatable(iris,
class = 'row-border stripe hover compact',
rownames = F,
autoHideNavigation = T, escape =FALSE) %>%
formatStyle(columns = c("Sepal.Length"), fontWeight = 'bold', `text-align` = 'left') %>%
formatStyle(columns = c("Petal.Length"), fontWeight = 'bold', `text-align` = 'right')
So far the only way I can get it to work is by manually setting the HTML tags first, and then using escape = FALSE
Here we wrap Sepal.Length in the bold HTML tag:
iris$SepalLength2 <- paste0("<b>", iris$Sepal.Length, "</b>")>
Then use escape = FALSE so that the HTML tags are parsed.
datatable(iris,
class = 'row-border stripe hover compact',
rownames = F,
autoHideNavigation = T, escape =FALSE)
Edit:
For align left/right, you can wrap in a <p align ="left"></p>
So: iris$SepalLength2 <- paste0('<p align ="right"><b>', iris$Sepal.Length, '</b></p>')
Note that I am neither an HTML guru, nor an expert on this particular library, but this seems like one way to get your desired result.
You don't need to modify the contents of your data. Instead, you can use the rowCallback option:
library(DT)
rowCallback <- c(
"function(row, data, index){",
" $(this.api().cell(index, 0).node())",
" .css('text-align', 'left')",
" .css('font-weight', 'bold');",
" $(this.api().cell(index, 2).node())",
" .css('text-align', 'right')",
" .css('font-weight', 'bold');",
"}"
)
DT::datatable(iris,
class = 'row-border stripe hover compact',
rownames = FALSE,
autoHideNavigation = TRUE,
options = list(pageLength = 5,
searching = FALSE,
paging = TRUE,
info = FALSE,
rowCallback = JS(rowCallback))
)