在R中聚合每个组的唯一字符值

问题描述 投票:1回答:2

我想按组聚合特定年份的所有关键字。

我有一个看起来像这样的数据集:enter image description here

对我来说,主要的问题是Words列可以在1到52之间变化!我想在不同的列中拆分此列,然后使用group_by。但现在我不知道该怎么办。

r group-by dplyr uniqueidentifier
2个回答
1
投票

我们可以将'Words'分成listvector,将unnest分成'long'格式,删除重复的行,按'Year','UID'分组,paste将'Words'分成单个字符串

library(dplyr)
df1 %>% 
    mutate(Words = strsplit(Words, ",")) %>% 
    unnest %>% 
    distinct(Year, UID, Words) %>% 
    group_by(UID, Year) %>% 
    summarise(Words = toString(Words))
# A tibble: 4 x 3
# Groups:   UID [?]
#    UID  Year Words                                    
#  <dbl> <dbl> <chr>                                    
#1    10  2009 ABC, CDEFGH, LMX, ABCD, IJKLM, PQRS, EFGH
#2    11  2010 BDFC, CDE, PQRS, ACCA, IJKLM             
#3    12  2010 ABCD, CADDE                              
#4    12  2011 ABC, CDE, EFGH       

data

df1 <- structure(list(ID = c(1, 2, 3, 4, 5, 6, 5), Year = c(2011, 2011, 
2010, 2010, 2009, 2010, 2009), UID = c(12, 12, 11, 12, 10, 11, 
10), Words = c("ABC,CDE", "EFGH,CDE", "BDFC,CDE,PQRS", "ABCD,CADDE", 
"ABC,CDEFGH,LMX,ABCD,IJKLM,PQRS", "BDFC,ACCA,IJKLM", "EFGH")),
 class = "data.frame", row.names = c(NA, -7L))

0
投票

aggregate的基础R方法:

df <- data.frame(
    id = c(1:5, 6, 5),
    year = c(2011, 2011, 2010, 2010, 2009, 2010, 2009),
    uid = c(12, 12, 11, 12, 10, 11, 10),
    words = c("abc,cde", "efgh,cde", "bdfc,cde,pqrs", "abcd,cadde", "abc,cdefgh,lmx,abcd,ijklm,pqrs","bdfc,acca,ijklm", "efgh"),
    stringsAsFactors = FALSE
)

aggregate(df["words"], df[,c("year", "uid")], function(x) paste0(unique(unlist(strsplit(x, ","))), collapse=","))
© www.soinside.com 2019 - 2024. All rights reserved.