Folks, I need an elegant way of creating frequency count and group by multiple variables. Output should be a dataframe. I know the answer lies somewhere in using dplyr and data.table which I am still learning. I tried this link but I want to do this using dplyr and data.table.
Here is the sample data from the same 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)
Here is the output I am looking for. Thanks and appreciate your help!
We can use dcast
from data.table
library(data.table)
dcast(setDT(Survey), Age + Sex ~Health, value.var = "Country",
length)[, Total := Average + Good + Poor][]
If we don't want to type the column names, use Reduce
with +
dcast(setDT(Survey), Age + Sex ~Health, value.var = "Country",
length)[, Total := Reduce(`+`, .SD), .SDcols = Average:Poor][]
Here is a method using data.table
and tidyr
but not dcast
. First, you count observations with .N
in j
by the variables of interest
Survey[, .N, by=.(Age, Sex, Health)]
returning:
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
Then, use spread
from tidyr
to turn your column of choice into a set of new columns (one for each unique value) populated by N
spread(Survey[, .N, by=.(Age, Sex, Health)], Health, N)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.