频率 table 并按 r 中的多个变量分组

frequency table and group by multiple variables in r

伙计们,我需要一种优雅的方法来创建频率计数和按多个变量分组。输出应该是一个数据框。我知道答案在于使用我仍在学习的 dplyr 和 data.table。 我试过 link 但我想使用 dplyr 和 data.table.

这是来自同一个 link -

的示例数据
ID <- seq(1:177)
Age <- sample(c("0-15", "16-29", "30-44", "45-64", "65+"), 177, replace = TRUE)
Sex <- sample(c("Male", "Female"), 177, replace = TRUE)
Country <- sample(c("England", "Wales", "Scotland", "N. Ireland"), 177, replace = TRUE)
Health <- sample(c("Poor", "Average", "Good"), 177, replace = TRUE)
Survey <- data.frame(Age, Sex, Country, Health)

这是我正在寻找的输出。感谢并感谢您的帮助!

我们可以使用 dcast 来自 data.table

library(data.table)
dcast(setDT(Survey), Age + Sex ~Health, value.var = "Country",
                   length)[, Total := Average + Good + Poor][]

如果我们不想键入列名,请使用 Reduce+

dcast(setDT(Survey), Age + Sex ~Health, value.var = "Country",
                length)[, Total := Reduce(`+`, .SD), .SDcols = Average:Poor][]

这是一个使用 data.tabletidyr 而不是 dcast 的方法。首先,您通过感兴趣的变量

计算 j.N 的观察值

Survey[, .N, by=.(Age, Sex, Health)]

返回:

 Age   Sex     Health   N
 30-44 Female  Average  10
 65+   Female  Poor     9
 0-15  Male    Average  3
 16-29 Male    Average  6
 30-44 Male    Good     6
 45-64 Female  Average  8

然后,使用 tidyr 中的 spread 将您选择的列变成一组由 N

填充的新列(每个唯一值一个)

spread(Survey[, .N, by=.(Age, Sex, Health)], Health, N)