如何计算列表中每个项目与其他每个项目同时出现的次数?

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

这个领域有很多问题,都有很好的解决方案,但我很难将它们应用到我的数据中。我有长格式数据,其中一列为我们提供观察结果,另一列为我们提供观察结果中的成员。我想做的就是计算每个成员与其他成员同时出现的次数。

假设我有以下数据集:

df <- data.frame(salad = c(rep("Green", 4), rep("Caprese", 3), rep("Fruit", 3)),
                 ingredients = c("Lettuce", "Tomato", "Onion", "Olives",
                                 "Tomato", "Onion", "Mozzarella",
                                 "Melon", "Orange", "Tomato"))

df

     salad ingredients
1    Green     Lettuce
2    Green      Tomato
3    Green       Onion
4    Green      Olives
5  Caprese      Tomato
6  Caprese       Onion
7  Caprese  Mozzarella
8    Fruit       Melon
9    Fruit      Orange
10   Fruit      Tomato

我想要做的是生成一个包含所有可能的成员(成分)组合的表格,并计算它们在观察(沙拉)中同时出现的次数。它看起来像这样:

results

    ingredient_A     ingredient_B      count
1   Lettuce          Tomato            1
2   Lettuce          Onion             1
3   Lettuce          Olives            1
4   Lettuce          Mozzarella    0
5   Lettuce          Melon             0
6   Lettuce          Orange            0
7   Tomato           Onion             2
8   Tomato           Olives            1
9   Tomato           Mozzarella    1
10  Tomato           Melon             1
…   …            …             …

我觉得答案非常简单,但我现在遇到了困难。任何帮助将不胜感激。

r count
1个回答
0
投票

这是 dplyr/tidyr 方法:

library(dplyr)
library(tidyr)
df %>%
  left_join(., ., by = join_by(salad, ingredients < ingredients), suffix = c("_A", "_B")) %>%
  filter(complete.cases(.)) %>% 
  count(ingredients_A, ingredients_B)
#    ingredients_A ingredients_B n
# 1        Lettuce        Olives 1
# 2        Lettuce         Onion 1
# 3        Lettuce        Tomato 1
# 4          Melon        Orange 1
# 5          Melon        Tomato 1
# 6     Mozzarella         Onion 1
# 7     Mozzarella        Tomato 1
# 8         Olives         Onion 1
# 9         Olives        Tomato 1
# 10         Onion        Tomato 2
# 11        Orange        Tomato 1
© www.soinside.com 2019 - 2024. All rights reserved.