我想按组聚合特定年份的所有关键字。
对我来说,主要的问题是Words列可以在1到52之间变化!我想在不同的列中拆分此列,然后使用group_by。但现在我不知道该怎么办。
我们可以将'Words'分成list
的vector
,将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
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))
与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=","))