Search code examples
rformattable

How to call or use formattable on a table


I've got a dataframe my_df containing the two columns gender (m/f) and sick (yes/no). I created a contingency table out of these two using:

my_table <- addmargins(table(my_df$gender, my_df$sick))

Now i want to style up this very basic output by using the formattable::formattable() function i just found but i am failing at one of first steps as the call formattable(my_table) does return the same as just my_table. What am I missing?

Currently trying with this guide: https://www.littlemissdata.com/blog/prettytables

First time posting after a few weeks of lurking to get somehow started with R. Hope i stayed within etiquette.

Best regards tholori


Solution

  • I had a look in the docs. formattable works on data.frames not table objects. To work with your table you have to convert it to a data.frame. As the conversion breaks the table layout you have to reshape the resulting df, e.g. by spread from tidyr.

    library(dplyr)
    library(tidyr)
    library(formattable)
    
    # example data = mtcars
    my_table <- addmargins(table(factor(mtcars$cyl), factor(mtcars$gear))) %>% 
      as.data.frame() %>% 
      spread(Var2, Freq)
    
    formattable(my_table)