我有一个按 ID 和几种水果排序的数据集。我想要做的是根据 ID 检测 2 种水果的所有可能组合而不重复(Apple-Banana 组合应该与 Banana-Apple 相同)。
举个例子:
我要创建的是:
示例数据集:
ID <- c(1,1,1,2,3,3,3,3)
Fruit <- c("Apple","Banana","Blueberry","Apple","Orange","Banana","Apple","Blueberry")
dataset <- data.frame(ID, Fruit)
最佳答案
使用dplyr
,你可以使用summarise
+ combn
:
library(dplyr)
dataset %>%
group_by(ID) %>%
summarise(Fruit = if(n() > 1) combn(Fruit, 2, simplify = FALSE) else list(Fruit))
# # A tibble: 10 × 2
# # Groups: ID [3]
# ID Fruit
# <dbl> <list>
# 1 1 <chr [2]>
# 2 1 <chr [2]>
# 3 1 <chr [2]>
# 4 2 <chr [1]>
# 5 3 <chr [2]>
# 6 3 <chr [2]>
# 7 3 <chr [2]>
# 8 3 <chr [2]>
# 9 3 <chr [2]>
# 10 3 <chr [2]>
其中 Fruit
是一个列表列,其中包含每个 ID
的每对水果。
如果您想折叠列表的每个元素以字符 vector-column 结尾,只需将 FUN = toString
添加到combn()
.
(注意两种方法的 else
语句的区别,前者是 else list(Fruit)
而后者只是 < em>else 水果
)
dataset %>%
group_by(ID) %>%
summarise(Fruit = if(n() > 1) combn(Fruit, 2, FUN = toString) else Fruit)
# # A tibble: 10 × 2
# # Groups: ID [3]
# ID Fruit
# <dbl> <chr>
# 1 1 Apple, Banana
# 2 1 Apple, Blueberry
# 3 1 Banana, Blueberry
# 4 2 Apple
# 5 3 Orange, Banana
# 6 3 Orange, Apple
# 7 3 Orange, Blueberry
# 8 3 Banana, Apple
# 9 3 Banana, Blueberry
# 10 3 Apple, Blueberry
关于r - 在R中的数据集中通过id查找两个字符的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73246504/