转置来自 dplyr 或 gt 的结果 table

Transpose result table from dplyr or gt

我正在使用 dplyrgt 来尝试生成摘要 table。这是我的示例数据:

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

这是我的代码:

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()

结果是相当宽的格式。我想知道如何在长格式中重新排列 table,例如:

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

使用 pivot_longerpivot_wider 你可以:

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()