伙计们,我需要一种优雅的方法来创建频率计数和多个变量分组。输出应该是数据帧。我知道答案在于使用dplyr和data.table,我还在学习。 我试过这个link但是我想用dplyr和data.table来做这个。
以下是来自同一链接的示例数据 -
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)
这是我要找的输出。谢谢,感谢您的帮助!
答案 0 :(得分:3)
我们可以使用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][]
答案 1 :(得分:1)
以下是使用data.table
和tidyr
但不使用dcast
的方法。首先,您通过感兴趣的变量
.N
中j
的观察结果
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
然后,使用spread
中的tidyr
将您选择的列转换为由N
填充的一组新列(每个唯一值一列)
spread(Survey[, .N, by=.(Age, Sex, Health)], Health, N)