如何汇总因子变量?

时间:2019-02-18 08:55:50

标签: r aggregate

我有一个如下数据框:

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

现在,我想汇总IDcountry变量上的值,因此,我使用:

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变量是一个因素,所以我不知道如何将其合并到汇总表中。对于一个ID,factor变量的值始终是相同的,因此我只需要在聚合表中为style变量打印style变量的第一个值。有谁知道该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以只使用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

这两种方法都假设styleID的{​​{1}}始终相同。


样本数据

month