r - 在R中的数据集中通过id查找两个字符的组合

标签 r dataframe group-by combinations

我有一个按 ID 和几种水果排序的数据集。我想要做的是根据 ID 检测 2 种水果的所有可能组合而不重复(Apple-Banana 组合应该与 Banana-Apple 相同)。

举个例子:

<表类="s-表"> <头> 身份证 水果 <正文> 1 苹果 1 香蕉 1 蓝莓 2 苹果 3 橙色 3 香蕉 3 苹果 3 蓝莓

我要创建的是:

<表类="s-表"> <头> 身份证 组合 <正文> 1 苹果香蕉 1 苹果蓝莓 1 香蕉蓝莓 2 苹果 3 香蕉橙 3 苹果橙 3 蓝莓橙 3 苹果香蕉 3 香蕉蓝莓 3 苹果蓝莓

示例数据集:

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/

相关文章:

r - 根据条件对组的数据帧的不同级别进行计数

python - Pandas Python 上的 Group by 和 where 查询

r - 根据 data.frame 中的(组)值扩展 data.frame

python - 使用 ~isin([list_of_substrings]) 过滤 Dataframe

r - data.table 按名称引用另一个 data.table 中的列

Python Pandas 将多列零替换为 Nan

python - 需要将数据框的列值转换为单独的列,并使用 panda 填充每个单元格的计数值

php - 如何限制/偏移每个唯一 ID 返回多行的查询?

r - 在字符串条件下子集 df

r - 在 R 中的函数中保存 Stata 文件