簡體   English   中英

如何聚合因子變量?

[英]How to aggregate factor variable?

我有一個如下所示的數據框:

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總是相同的,所以我只需要打印聚合表中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

這兩種方法都假定每個IDmonth style始終相同。


樣本數據

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM