Creating a function of DT table in shiny - r

I am trying to create a function for DT table where just specifying the columns name in the parameter, the column should get hidden
dt_table <- function(data,
colhidden = c(a)){
datatable(data,
options = list(
columnDefs = list(
list(visible=FALSE, targets=colhidden)
)
))
}
dt_table(iris,colhidden = c('Species'))
But unfortunately, the column is not getting hidden. Can anyone help me?

targets needs the column number which you can get with match. Try -
library(DT)
dt_table <- function(data, colhidden) {
datatable(data,
options = list(
columnDefs = list(
list(visible=FALSE, targets=match(colhidden, colnames(data))))
)
)
}
dt_table(iris,colhidden = c('Species'))
dt_table(iris,colhidden = c('Species', 'Sepal.Length'))

Related

How to preserve order in shiny app using datatables when sorting in the app?

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)

R reactable - applying multiple styles in colDef

Columns in reactable (R package reactable) can be styled with a list of styles, a function or javascript - which works if I want to use one way only. How can these be combined (without rewriting the list, function or javascript code?
Example:
library(reactable)
list_style <- list(background = "#eee")
js_style <- JS("
function(rowInfo) {
return {fontWeight: 'bold' }
}
")
fn_style <- function(value) {
color <- "#008000"
list(color = color)
}
df <- data.frame(x = 1:10, y = 11:20)
reactable(
df,
columns = list(
x = colDef(
style = c(list_style, js_style, fn_style) # This generates the below error
)
)
)
Error:
Error in colDef(style = c(list_style, js_style, fn_style)) :
`style` must be a named list, character string, JS function, or R function
reactable(
df,
columns = list(
x = colDef(
style = list(list_style, js_style, fn_style)
)
)
)
it seems that your style out of list, please replace those code with this reactable

Automatic line break in DT cell

I'm displaying a list in a cell of a DT table :
mylist <- paste0("name",1:20)
data <- data.frame(id = 1, members = I(list(mylist)))
DT::datatable(data)
The list appears on a single very long line:
I would like to have an automatic line break so that the list is split in many lines inside the cell, preferably according to the width of the cell.
[EDIT] this is the expected result, see accepted Answer :
I tried without success to set DT ColumnDefs options :
DT::datatable(data,options = list(
autoWidth= T,
columnDefs = list(list(width = "200" ))
))
Looks tricky as there seem to be an issue on width option
Thanks for your help
Instead of using a list you can use the string "name1, name2, ...".
mylist <- paste0("name",1:20)
data <- data.frame(id = 1, members = toString(mylist))
datatable(data, options = list(
columnDefs = list(
list(width = 200, targets = 2)
)
))

R DT::datatables formatting multiple columns simultaneously

I wish to implement formatCurrency() and formatPercentage() (both from DT package) across multiple columns simultaneously in a shiny dashboard. I am using shinymaterial for the given example.
I am currently doing the following:
# The packages to load.
required_packages <- c("shiny", "shinymaterial", "DT", "tidyverse")
# This function will load in all the packages needed.
lapply(required_packages, require, character.only = TRUE)
# A table example.
ui <- material_page(
title = "Example table",
tags$h1("Table example"),
material_card(
title = "Table",
material_row(
DT::dataTableOutput("data_table_example")
),
depth = 1
)
)
server <- function(input, output) {
data_table_example_data = tibble(
Person = paste0("Person ", c(1:100)),
`Price $` = rnorm(100, 50000, 500),
`Cost $` = rnorm(100, 30000, 300),
`Probability %` = rnorm(100, 0.6, 0.1),
`Win %` = rnorm(100, 0.5, 0.2)
)
# This will create an output summary table
output$data_table_example = renderDataTable({
result = datatable(data_table_example_data, options = list(pageLength = 100, scrollX = TRUE),
class = 'cell-border stripe compact', rownames = FALSE) %>%
formatCurrency("Price $") %>%
formatCurrency("Cost $") %>%
formatPercentage("Probability %", digits = 1) %>%
formatPercentage("Win %", digits = 1)
})
}
shinyApp(ui = ui, server = server)
However, what I wish to do is, within the renderDataTable() function, to simplify the format functions into fewer lines. For example, implement formatCurrency() in any column with a "$" and formatPercentage() in any column with a "%".
I have done a fair bit of searching for an appropriate but could not find a solution, but I assume I am just missing a fairly simple solution.
Something like:
# This will create an output summary table
output$data_table_example = renderDataTable({
result = datatable(data_table_example_data, options = list(pageLength = 100, scrollX = TRUE),
class = 'cell-border stripe compact', rownames = FALSE) %>%
formatCurrency(grepl("$", colnames()) %>%
formatPercentage(grepl("%", colnames()), digits = 1)
})
A few additional points:
The tibble will actually be a reactive
This example is a very trivial version of a rather more complex table and set of reactives
I do not want to implement the formatting in the reactive part since I find this then messes with the DT sorting function, since it assumes the column is a character string
Any help will be greatly appreciated
Try:
# This will create an output summary table
output$data_table_example = renderDataTable({
result = datatable(data_table_example_data, options = list(pageLength = 100, scrollX = TRUE),
class = 'cell-border stripe compact', rownames = FALSE) %>%
formatCurrency(grepl("$", colnames(data_table_example_data)) %>%
formatPercentage(grepl("%", colnames(data_table_example_data)), digits = 1)
})
It seems you need to be explicit with the data so colnames() doesn't work - you need colnames(data_table_example_data).
I noticed during testing if you use grepl with rownames = TRUE that rownames becomes the first column name which means all the formatting is out by one. grep seems to not have this issue.

Shiny: Removing record numbering from DataRenderTable

I have below code:
t_af_ts_outcomes <- datatable( data = cars
, options = list( bFilter = 0
, bLengthChange = 0
, paging = F
, info = F
)
)
output$v_af_ts_outcomes <- renderDataTable( t_af_ts_outcomes )
And it gives below output:
Is there anyway I can remove the row numbers?
Set argument rownames = FALSE inside datatable() function.

Resources