Search code examples
rdatatableformattingdtflexdashboard

DT::datatable in R, flexdashboard


 Household Size    0       1          2        3        4        5+
                 Bedrooms Bedrooms Bedrooms Bedrooms Bedrooms Bedrooms
       1          253   4486        2033     930        105      8
       2          10    666         3703     947        85       7
       3           4    68          1972     1621       52       5
       4           1    12           680     1835       164      11
      5+           0    6            147     1230       721      122

I have the above dataframe where 'Bedrooms' is a label on the columns.

I'm trying to change this into a data table I can then use within rmarkdown to add into a flexdashboard. When I use the below code:

DT::datatable(df, rownames = FALSE, extensions = 'FixedColumns', escape=TRUE,options= list(bPaginate = FALSE))

I get the output:

Household Size         0    1      2       3     4        5+
1                    253    4486  2033    930   105       8
2                     10    666   3703    947   85        7
3                      4    68    1972    1621  52        5
4                      1    12     680    1835  164       11
5+                     0    6      147    1230  721       122

I have a few problems with this:

  1. The lables that say 'Bedrooms' don't show, so there's no way of knowing what these numbers in the columns actually mean. I'd like to include the labels or have a Row on top of the column names that says "Number of Bedrooms" that covers all of the rows?
  2. The column Household Size and 5+ have a wider width than the rest of the columns, I want these to either be the same or Household Size to be slightly bigger than the rest

I think it's worth noting that the row 5+ and the column 5+ are both a new row/column that count any value above 5.

Also, this is just an extra but I'd like to colour the bottom left cells red and the top right cells green, is this possible?


Solution

  • I've figured out how to keep 'Bedrooms' in the column titles. It's possible to set the column names within DT::datatable using the code below;

    DT::datatable(HS_BED_ALL, rownames = FALSE, colnames=c('Household Size','0 Bedrooms','1 Bedroom','2 Bedrooms','3 Bedrooms','4 Bedrooms','5+ Bedrooms'), extensions = 'FixedColumns', escape=TRUE, options= list(bPaginate = FALSE, dom = 't',buttons = c('excel')))%>%formatStyle(1:7,fontSize = '14px')
    

    Which gives the desired output.