簡體   English   中英

如何創建兩組數據框的所有組合?

[英]How to create two groups of all combinations of a dataframe?

我有一個像這里的例子的數據框:

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 循環是最好的方法,但我什至不知道如何開始。

這是一個 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM