[英]Find two columns that match in two dataframes and put third column from dataframe 2 into a new column in dataframe 1 using R
[英]How to merge two columns from different dataframes into a new dataframe by a third key variable (R)
我有這兩個數據框:
df1 <- data.frame(a= c(1,2,3,1,2,3,1,2,3), b=c(11,21,31,12,22,32,13,23, 33))
df2 <- data.frame(a= c(1,2,3,1,2,3,1,2,3), c=c(101,201,301,102,202,302,103,203,303))
我想將列“b”和“c”合並到一個新的數據框中,但使用“a”作為關鍵變量。
預期的結果是這樣的:
df.output <- data.frame(b=c(21,22,23), c=c(201,202,203))
我已經嘗試過 dplyr 的 join 功能,但沒有成功。
謝謝,
克勒門
編輯
根據 OP 的其他評論,調整原始解決方案可以實現所需的輸出(盡管我認為@akrun 的答案是在這種情況下選擇的更好的答案,因為不需要nest
/ unnest
nest
)。
library(tidyverse)
left_join(nest(df1, -a), nest(df2, -a), by = "a") %>%
filter(a == 2) %>% unnest() %>% select(-a)
#> b c
#> 1 21 201
#> 2 22 202
#> 3 23 203
原答案
正如@akrun 在評論中提到的,所需的輸出並不完全清楚。 你的意思是像這樣的輸出嗎?
library(tidyverse)
df3 <- left_join(nest(df1, -a), nest(df2, -a), by = "a")
df3
#> a data.x data.y
#> 1 1 11, 12, 13 101, 102, 103
#> 2 2 21, 22, 23 201, 202, 203
#> 3 3 31, 32, 33 301, 302, 303
根據 OP 在評論中提到的邏輯,我們可以只filter
'a' 中值為 2 的行,然后通過獲取相應的 'c' 值來mutate
列 'c' 的值是 'a' is 2
library(dplyr)
df1 %>%
filter(a == 2) %>%
mutate(c = df2$c[a ==df2$a]) %>%
select(-a)
# b c
#1 21 201
#2 22 202
#3 23 203
或使用base R
cbind(subset(df1, a==2, select = b), subset(df2, a==2, select = c))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.