rdplyrkableextracolumn-width

kableExtra column_spec error - maybe dplyr summarise


I'm encountering strange behaviour with kableExtra column_widths and I'm not sure whether it's due to the most recent release of kableExtra or due to the newly implemented "groups" parameter in dplyr's summarise function.

If I create a dataframe like this ...

 Summary <- mtcars %>% 
            group_by(cyl, gear, carb) %>% 
            summarise(count = n(), .groups = "keep") %>% 
            arrange(desc(cyl))

and then attempt to tabulate the data frame using kableExtra like this ...

 kable((Summary), caption = "mtcars Data Summary\n", align = c('l','l','c','c')) %>%
                  kable_styling(bootstrap_options = c("striped","hover"),full_width = FALSE, position = "left") %>% 
                  collapse_rows(columns = 1, valign = "top") %>% 
                  column_spec(1, width = "3cm") %>% column_spec(2, width = "3cm") %>% 
                  column_spec(3, width = "2cm") %>% column_spec(4, width = "2cm")

I get this error -

Error in xml_children(x)[[search]] : subscript out of bounds

I totally understand this error in the context of having attempted to specify a column width for a column that doesn't exist but this dataframe, created by the summarise function, clearly contains 4 columns ...

Rows: 12
Columns: 4
Groups: cyl, gear, carb [12]
$ cyl 8, 8, 8, 8, 8, 6, 6, 6, 4, 4, 4, 4
$ gear 3, 3, 3, 5, 5, 3, 4, 5, 3, 4, 4, 5
$ carb 2, 3, 4, 4, 8, 1, 4, 6, 1, 1, 2, 2
$ count 4, 3, 5, 1, 1, 2, 4, 1, 1, 4, 4, 2

so I can't understand how this error is happening. Also if I remove the column width setting for column #4 then the table is output as expected (minus the desired width of column #4)

I was wondering if this is due to the recent updates to kableExtra (now on 1.3.1) or due to the new ".groups" parameter in dplyr summarise (now on 1.0.2) - but I have tried all the valid values of .groups = "..." with no success.


Solution

  • Add the collapse_rows function at the end.

    library(kableExtra)
    
    Summary <- mtcars %>% 
                group_by(cyl, gear, carb) %>% 
                summarise(count = n(), .groups = "keep") %>% 
                arrange(desc(cyl))
    
    Table <- kbl(Summary, caption = "mtcars Data Summary\n", align = c('l','l','c','c')) %>%
             kable_styling(bootstrap_options = c("striped","hover"),full_width = FALSE, position = "left") %>% 
             column_spec(1, width = "3cm") %>% column_spec(2, width = "3cm") %>% 
             column_spec(3, width = "2cm") %>% column_spec(4, width = "2cm")
    
    Table <- Table %>% 
             collapse_rows(columns = 1, valign = "top")