r - 如何聚合因子变量?
问题描述
我有一个如下所示的数据框:
ID month country count style
1 2012-02 UK 3 high
1 2012-02 US 10 high
1 2012-02 FR 5 high
etc
现在,我想聚合ID
andcountry
变量上的值,因此,我使用:
aggregated_data = setDT(subset)[, .(Country = list(Country), ID = min(ID),
count = sum(count), by = list(Model, Month)][]
要得到
ID month country count
1 2012-02 UK, US, FR 18
etc
但是,由于我的style
变量是一个因素,我不知道如何将其合并到聚合表中。对于 one ,因子变量的值始终相同ID
,因此我只需要为聚合表中的style
变量打印变量的第一个值。style
有谁知道如何做到这一点?
解决方案
你可以只使用unique
,例如
df <- setDT(df)
df[, .(country = toString(country), count = sum(count), style = unique(style)), by = list(ID, month)]
# ID month country count style
#1: 1 2012-02 UK, US, FR 18 high
或使用dplyr
df %>%
group_by(ID, month) %>%
summarise(
country = toString(country),
count = sum(count),
style = unique(style))
## A tibble: 1 x 5
## Groups: ID [?]
# ID month country count style
# <int> <fct> <chr> <int> <fct>
#1 1 2012-02 UK, US, FR 18 high
两种方法都假设和style
始终相同。ID
month
样本数据
df <- read.table(text =
"ID month country count style
1 2012-02 UK 3 high
1 2012-02 US 10 high
1 2012-02 FR 5 high", header = T)
推荐阅读
- python - 为什么pygame中的这个文本打印功能会造成延迟?
- c# - 使用反射的动态创建的类的 getter 和 setter 的 C# 动态委托
- python - Python - Holoviews 没有图像
- c - C中的字符数组和字符串终止字符
- css - 网格不听单元格的“最小宽度:最小内容”
- android - 我无法运行 Espresso 测试
- typescript - 打字稿工厂函数签名
- node.js - bcrypt.compare 与 Promise 总是返回 false
- c# - Bot framework v4 循环对话框参考
- c# - Linq 查询不会从另一个对象中的对象返回结果