[英]Is there an R function to merge two data frames based on two columns separately matching to the same column?
[英]In R, apply a function separately between columns with same names in different data frames
我有兩個數據框:
require(tidyverse)
set.seed(42)
df1 = data_frame(x = c(4,3), y = c(0, 0), z = c(NA, 3))
df2 = data_frame(x = sample(1:4, 100, replace = T), y = sample(c(-3, 0, 3), 100, replace = T), z = c(NA, NA, rep(3, 98))) %>% mutate(Tracking = row_number())
我想單獨對每行df1
並為每列df1
找到的指數df2
為其df2
等於df1
。 如果我嘗試循環,則每次迭代都將如下所示:
for (i in 1: nrow(df1)){
for (j in 1: ncol(df1)) {
L[[i]][j] = inner_join(df1[i,j], df2)
}
}
例如,列表的第一個元素是:
inner_join(df1[1,1], df2)
Joining, by = "x"
# A tibble: 26 x 4
x y z Tracking
<dbl> <dbl> <dbl> <int>
1 4. 0. NA 1
2 4. -3. NA 2
3 4. 0. 3. 4
4 4. 3. 3. 13
5 4. 0. 3. 16
6 4. -3. 3. 17
7 4. 0. 3. 21
8 4. 0. 3. 23
9 4. 0. 3. 24
10 4. 3. 3. 28
# ... with 16 more rows
但是,我相信有一種更有效的方法可以做到這一點。 可能是dplyr
+ purrr
嗎? 我沒有關於purrr
豐富經驗,但是我覺得map
函數可以派上用場。 我只是不知道如何分別調用列。
你可以做類似的事情
L <- map(names(df1),
function(.) {
out <- inner_join(x = df1[, ., drop = FALSE],
y = df2,
by = .)
split(out, out[[.]])
})
但是我不確定這是否比開始的for循環更好或更有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.