I need to set the column width of a DataTabe in an R Shiny app. I went through the Data Table Options in the documentation. Also, I reviewed this and this questions in Stackoverflow.
Setting width works fine if the DataTable does not have too many columns. In cases, however, if multiple columns present the settings is overridden despite the absolute width unit (e.g. '600px'
).
In the below code snippet:
output$mytable <- DT::renderDataTable({
num_of_cols <- 3
cbind(iris,iris)[,1:num_of_cols]},
options = list(autoWidth = TRUE,
columnDefs = list(list(width = '500px', targets = 1))))
if I set variable num_of_cols = 3
it works fine. Increasing displayed columns (num_of_cols
), however, leads to decrease in column width. In case of lots of displayed columns the width setting seemingly has no effect.
I tried option autoWidth = FALSE
but it gives no different result. I also tried using JavaScript in options drawCallback
as described in the answer section of this thread but it gives the same result.
How can I have DataTable display the desired column width setting?
Wow. I can't believe this. Column width on a table object should be so clear and yet for data tables it was so confusing. I spent a lot of time researching this and coming up dry before finally discovering the answer in the tool tip displays in RStudio.
DT::renderDataTable({
datatable(df) %>% formatStyle(columns = c(1,2), width='200px')
})
EDIT:
This might work, but it doesn't actually work any better than any other way. There is no straight forward way to do this that I could tell. Here's the code I am NOW using... I don't think I will need to use anything else. I had to build it out column by column and continually go back and adjust to get it to work. Seems like something that should be fixed.
I set the UI width value to 1200px to start and scaled it back when I was all done.
#UI
DT::dataTableOutput(outputId = "tableID", width = '830px')
#Server
options = list(autoWidth = TRUE,
columnDefs = list(list(targets=c(0), visible=TRUE, width='90'),
list(targets=c(1), visible=TRUE, width='145'),
list(targets=c(2), visible=TRUE, width='105'),
list(targets=c(3), visible=TRUE, width='100'),
list(targets=c(4), visible=TRUE, width='100'),
list(targets=c(5), visible=TRUE, width='100'),
list(targets=c(6), visible=TRUE, width='100'),
list(targets=c(7), visible=TRUE, width='90'),
list(targets='_all', visible=FALSE)
As suggested here, setting scrollX=T
and keeping autoWidth = TRUE
in the options should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With