dplyr合并行和列,其中除一个列外的所有列都匹配
我的df如下所示:dplyr合并行和列,其中除一个列外的所有列都匹配,r,dplyr,R,Dplyr,我的df如下所示: ID Val1 Val2 Val3 0 2 3 4 1 5 3 2 2 3 4 3 3 4 5 9 3 2 5 9 除了Val1之外,所有的值都将匹配,所以我希望合并有重复ID的行,并合并与Val1不同的值。我的预期产出是: ID Val1 Val2 Val3 0 2 3 4 1 5 3 2 2 3 4 3 3
ID Val1 Val2 Val3
0 2 3 4
1 5 3 2
2 3 4 3
3 4 5 9
3 2 5 9
除了Val1之外,所有的值都将匹配,所以我希望合并有重复ID的行,并合并与Val1不同的值。我的预期产出是:
ID Val1 Val2 Val3
0 2 3 4
1 5 3 2
2 3 4 3
3 4,2 5 9
aggregate
函数似乎很接近,但并不完全符合我的要求。我们可以通过“ID”进行分组,并通过获取主题的唯一值并包装在列表中来总结其他列
library(dplyr)
df1 %>%
group_by(ID) %>%
summarise_all(~ list(unique(.)))
或者,如果需要单个字符串,可以粘贴唯一的元素
library(stringr)
df1 %>%
group_by(ID) %>%
summarise_all(~ toString(unique(.)))
# A tibble: 4 x 4
# ID Val1 Val2 Val3
# <int> <chr> <chr> <chr>
#1 0 2 3 4
#2 1 5 3 2
#3 2 3 4 3
#4 3 4, 2 5 9
数据
df1第3行将是字符串,而不是数字。这就是你需要的吗?是的,那很好,我只是要计算这些值的出现次数,这样字符串就可以工作了
aggregate(.~ ID, df1, I) # creates list column
aggregate(.~ ID, df1, toString) # creates string
df1 <- structure(list(ID = c(0L, 1L, 2L, 3L, 3L), Val1 = c(2L, 5L, 3L,
4L, 2L), Val2 = c(3L, 3L, 4L, 5L, 5L), Val3 = c(4L, 2L, 3L, 9L,
9L)), class = "data.frame", row.names = c(NA, -5L))