How to create a table with multiple classification in R

Viewed 42

I am having problems in create a report table with a data frame like this:

   id sex    age    location
   1   m   0-17       Miami
   2   f  18-64 Los Angeles
   3   f over64     Ontario
   4   m  18-64       Paris
   5   m  18-64     Ontario
   6   m over64       Miami
   7   f over64       Miami
   8   f  18-64 Los Angeles
   9   m  18-64       Other
  10   m over64       Other

my desired table should look like this: Deired Table

Any idea how to do it.

1 Answers

I think if you look through the packages gt and gtsummary, you'll find what you're looking for. For example, this is close to the example you provided as your desired output.

library(gtsummary)
library(gt)

df1 <- read.table(header = T, 
                  text = "Id Sex Age Location # notice I capitalized names
1 m 0-17 Miami
2 f 18-64 Los.Angeles
3 f over64 Ontario
4 m 18-64 Paris
5 m 18-64 Ontario
6 m over64 Miami
7 f over64 Miami
8 f 18-64 Los.Angeles
9 m 18-64 Other
10 m over64 Other", sep = " ")

tbl_summary(df1[,2:4]) %>% add_n() %>% bold_labels

This is the output table.

enter image description here

If you want to customize it, pipe in as_gt() and then use any of the functions in the gt package to customize it further.

Related