0

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

stefan
  • 90,330
  • 6
  • 25
  • 51
tholori
  • 13
  • 2
  • Welcome to SO ! Can you provide a minimal reproducible example of your dataframe ? (see this link: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Also, right now, you do not specify specify any formatting display in your command. Can you clarify what is your desired output ? – dc37 Mar 09 '20 at 10:47
  • Thanks for the link. As the question is already answered i will leave it like this, but will definetly keep this in mind next time! – tholori Mar 09 '20 at 12:14

1 Answers1

0

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)
stefan
  • 90,330
  • 6
  • 25
  • 51