首页 > 解决方案 > 如何聚合因子变量?

问题描述

我有一个如下所示的数据框:

ID    month    country   count    style
1     2012-02  UK        3        high
1     2012-02  US        10       high
1     2012-02  FR        5        high
etc

现在,我想聚合IDandcountry变量上的值,因此,我使用:

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有谁知道如何做到这一点?

标签: raggregate

解决方案


你可以只使用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始终相同。IDmonth


样本数据

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)

推荐阅读