我有一個資料框串列。當資料框之間的列名稱匹配時,我想在所有資料框中取列值的并集。
這是一個玩具資料。
df1 <- data.frame(group = c("G1", "G1", "G1", "G1", "G1", "G2", "G2", "G2", "G1", "G1"),
Name = c("B", "B","B", "A", "A",'D',"D" , "E", "C", "C"), value = c(2,4,5,2,4,7, 1, 2,4,1))
df2 <- data.frame(group = c("G1", "G1", "G1", "G1", "G2", "G2", "G2", "G2" , "G1", "G1"),
Name = c("B", "B" , "A", "A", "D", "E", "E", "E", "C", "C"), value = c(2, 3, 5, 1, 7, 2, 4, 8, 9,1))
df <- rbind(df1, df2)
df.list <- split(df, f=df$group)
欲望輸出如下:
B = 2,3,4,5
A = 1,2,4,5
D = 1,7
E = 2,4,8
C = 1,4,9
uj5u.com熱心網友回復:
我將使用 tidyverse 來解決問題,并假設所需的輸出是向量串列。在解決方案中,我確保只保留和Name之間通用的。df1df2
library(tidyverse)
bind_rows(df1, df2) %>%
filter(Name %in% df1$Name, Name %in% df2$Name) %>%
split(.$Name) %>%
map(~ sort(unique(.x$value)))
輸出:
$A
[1] 1 2 4 5
$B
[1] 2 3 4 5
$C
[1] 1 4 9
$D
[1] 1 7
$E
[1] 2 4 8
如果有兩個以上的資料框,您可以將它們全部放在一個串列中,并使用此解決方案,該解決方案適用于任意數量的資料框。
library(tidyverse)
dfs = list(df1, df2)
# First identify the common names within the data frames
common_names = dfs %>%
map(`[[`, "Name") %>%
reduce(intersect)
common_names
#> [1] "B" "A" "D" "E" "C"
# Now we can do the same thing as earlier
dfs %>%
reduce(bind_rows) %>%
filter(Name %in% common_names) %>%
split(.$Name) %>%
map(~ sort(unique(.x$value)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/399780.html
下一篇:使用ForEach中的SwiftUI3.0.swipeActions,您如何在將ForEach的輸入引數傳遞給該視圖的同時將操作轉到另一個視圖?
