gt package how to format column summary rows : how to format summary values with numbers AND percent based on columns

Viewed 396

I have a frequency and relative frequency table.

jobs <- c("teacher", "teacher", "teacher", "teacher", "researcher", "researcher" , "researcher" , "researcher", "barman", "barman" )

jobs <- data.frame(jobs)

I want to format my summary row with numbers for n and with percent for my freq column :

  1. What I tried: all values are in percent :

    jobs %>%
     count(jobs) %>%
     mutate(frequence = n/sum(n))  %>%
     gt(rowname_col =  "jobs")  %>%  
     grand_summary_rows (
       columns = vars(n, frequence),
       fns = list(Total =~sum(.)),
       formatter = fmt_percent
      )
    
  2. What I tried: retourns me an error

    jobs %>%
      count(jobs) %>%
      mutate(frequence = n/sum(n))  %>%
      gt(rowname_col =  "jobs")  %>%  
      grand_summary_rows (
       columns = vars(n, frequence),
       fns = list(Total =~sum(.)),
       formatter = fmt_percent(columns = "frequence"),
       formatter = fmt_number(columns = "n")
      )
    
2 Answers

If you want to use different formatting for each of the summary rows, you can use two calls to grand_summary_rows, one for each column with different formatting specified.

jobs <- c("teacher", "teacher", "teacher", "teacher", "researcher", 
          "researcher" , "researcher" , "researcher", "barman", "barman" )
jobs <- data.frame(jobs)

jobs %>%
  count(jobs) %>%
  mutate(frequence = n/sum(n))  %>%
  gt(rowname_col =  "jobs")  %>%  
  grand_summary_rows (
    columns = "n",
    fns = list(Total =~sum(.)),
    formatter = fmt_number
  ) %>%
  grand_summary_rows (
    columns = "frequence",
    fns = list(Total =~sum(.)),
    formatter = fmt_percent
  )

Table with numeric and percent summary rows

Your first problem stumped me for a little while: data.frames take each vector as a named parameter

jobs_vector <- c("teacher", "teacher", "teacher", "teacher", "researcher", "researcher" , "researcher" , "researcher", "barman", "barman")
df <- data.frame(jobs = jobs_vector)

Your next problem is solved with the tabyl() function from the janitor package.

library(janitor)
tabyl(df, jobs)

Returns

enter image description here

To get a publication-quality table, you are right to use the gt package. Here are two gt's useful functions:

library(gt)
df1 %>% 
  gt(rowname_col = jobs) %>% 
  opt_row_striping() %>% 
  gtsave("myTable.png")

enter image description here

Related