频率表和r中的多个变量分组

时间:2017-01-31 04:14:33

标签: r count data.table dplyr frequency

伙计们,我需要一种优雅的方法来创建频率计数和多个变量分组。输出应该是数据帧。我知道答案在于使用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)

这是我要找的输出。谢谢,感谢您的帮助!

enter image description here

2 个答案:

答案 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.tabletidyr但不使用dcast的方法。首先,您通过感兴趣的变量

计算.Nj的观察结果

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)