gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:21:55 25 4
gpt4 key购买 nike

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

最佳答案

我们可以使用 data.table 中的 dcast

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][]

关于r - 频率表和 r 中的多个变量分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41949529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com