Search code examples
rdplyrgt

Transpose result table from dplyr or gt


I'm using dplyr and gt to try to produce a summary table. Here is my sample data:

structure(list(child.sex = structure(c(2L, 1L, 2L, 1L, 2L, 1L, 
2L, 1L, 1L, 1L), .Label = c("boy", "girl"), class = "factor"), 
    child.age = c(9, 9, 9, 9, 9, 10, 9, 9, 10, 9)), row.names = c(NA, 
10L), class = "data.frame")
   child.sex child.age
1       girl         9
2        boy         9
3       girl         9
4        boy         9
5       girl         9
6        boy        10
7       girl         9
8        boy         9
9        boy        10
10       boy         9

Here is my code:

dt %>%
  group_by(child.sex) %>%
  dplyr::summarise(n=n(),mean=mean(child.age),sd=sd(child.age),
                   min=min(child.age), max=max(child.age)) %>%
  as.data.frame() %>%
  gt()

The result is rather a wide format. I'm wondering how to rearrange the table in a long formate like:

       boy     girl
n       6       4
mean   9.333   9.000
sd     0.516   0.000
min     9       9
max     10      9

Solution

  • Using pivot_longer and pivot_wider you could do:

    library(dplyr)
    library(gt)
    library(tidyr)
    
    dt %>%
      group_by(child.sex) %>%
      dplyr::summarise(n=n(), mean=mean(child.age),sd=sd(child.age),
                       min=min(child.age), max=max(child.age)) %>% 
      pivot_longer(-child.sex) %>% 
      pivot_wider(names_from = "child.sex", values_from = "value") %>% 
      gt()
    

    enter image description here