提问者:小点点

如何创建两组数据帧的所有组合?


我有一个像这里示例的数据帧:

Site <- c(1, 2, 3, 4, 5, 6)
Compound_1 <- c(0.5, 0.25, 0.5, 0.75, 0, 0.25)
Compound_2 <- c(0.25, 0.5, 0.5, 0.75, 0.25, 0)
df <- data.frame(Site, Compound_1, Compound_2)

print (df)

我想通过将这些行分成两组来创建所有组合的单独数据帧。例如,在组合1中,组x将包括站点1和组y站点2-6。下一个组合将有组x包括站点2和组y站点1和3-6。鉴于我的数据帧中有六个“站点”,代码应该产生64种不同的组合。我希望最终格式为每个组合2个数据帧,其中还包括Compound_1和Compound_2的所有信息,而不仅仅是列出的站点编号。我猜for循环是最好的方法,但我甚至不知道如何开始。


共1个答案

匿名用户

这里有一个tidyverse方法:

library(tidyverse)

# enumerate all the possible combinations of sites and groups
grps <- c("x","y")
tibble(V1 = grps, V2 = grps, V3 = grps,
           V4 = grps, V5 = grps, V6 = grps) %>%
  complete(V1, V2, V3, V4, V5, V6) %>%
  mutate(combo_num = row_number(), .before = 1) %>%

  # reshape to long
  pivot_longer(-combo_num, names_to = "Site", ,
               names_transform = parse_number,
               values_to = "Group") %>%

  # join with original data
  left_join(df) -> output

这会生成一个包含所有组合的长表,每个站点都有其原始值。

Joining, by = "Site"
# A tibble: 384 × 5
   combo_num  Site Group Compound_1 Compound_2
       <int> <dbl> <chr>      <dbl>      <dbl>
 1         1     1 x           0.5        0.25
 2         1     2 x           0.25       0.5 
 3         1     3 x           0.5        0.5 
 4         1     4 x           0.75       0.75
 5         1     5 x           0          0.25
 6         1     6 x           0.25       0   
 7         2     1 x           0.5        0.25
 8         2     2 x           0.25       0.5 
 9         2     3 x           0.5        0.5 
10         2     4 x           0.75       0.75
# … with 374 more rows

从那里,我们可以根据需要进行总结。例如,要获取x站点的所有组合,

x_combos <- output %>%
  filter(Group == "x")

或者我们可以看看每个组合在组X中产生的权重:

output %>%
  filter(Group == "x") %>%
  group_by(combo_num) %>%
  summarize(across(Compound_1:Compound_2, sum))

# A tibble: 63 × 3
   combo_num Compound_1 Compound_2
       <int>      <dbl>      <dbl>
 1         1       2.25       2.25
 2         2       2          2.25
 3         3       2.25       2   
 4         4       2          2   
 5         5       1.5        1.5 
 6         6       1.25       1.5 
 7         7       1.5        1.25
 8         8       1.25       1.25
 9         9       1.75       1.75
10        10       1.5        1.75
# … with 53 more rows