我正在尝试使用 kableExtra / gt 包(或任何有效的)生成一个整洁的表,目标是让我的值列按不同的变量分组:
data <- data.frame(Name = c("Mary","Mary","Mary","Jane","Jane","Jane"),
Variables = c(letters[1:3],letters[1:3]),
Count = c(45, 76, 43, 23, 11, 46),
Percent = c(0.45, 0.56, 0.89, 0.65, 0.88, 0.91)) %>% arrange(Name, Variables)
# Desired output:
# a b c
# Count Percent | Count Percent | Count Percent
# Mary 45 45% 76 56% 43 89%
# Jane 23 65% 11 88% 46 91%
我似乎不知道该怎么做,而我最接近的是:
library(gt)
gt(data, rowname_col = "Variables", groupname_col = "Name")
我从本页显示的图表中获得灵感: 按年份变量分组的输出列表
谢谢你的帮助!
更新:根据 Stefan 的帖子解决:
data <- data.frame(Name = c("Mary","Mary","Mary","Jane","Jane","Jane"),
Variables = c(letters[1:3],letters[1:3]),
Count = c(45, 76, 43, 23, 11, 46),
Percent = c(0.45, 0.56, 0.89, 0.65, 0.88, 0.91)) %>%
arrange(desc(Name), Variables)
# Helper to put the columns in the right order
cols_order <- unlist(lapply(c("a", "b", "c"), function(x) paste(x, c("Count", "Percent"), sep = "_")))
data_wide <- data %>%
pivot_wider(names_from = "Variables", values_from = c(Count, Percent), names_glue = "{Variables}_{.value}") %>%
# Reorder columns
select(all_of(c("Name", cols_order)))
data_wide %>%
gt(rowname_col = "Name") %>%
tab_spanner_delim(delim = "_") %>%
fmt_percent(ends_with("Percent"), decimals = 0)