[英]Merging same column from a dataset onto all of the columns of another in R?
I'm trying to do multiple merges/joins onto different columns in the same dataset, but when I do so the output is entirely wrong.我正在尝试对同一数据集中的不同列进行多次合并/连接,但是当我这样做时,output 是完全错误的。
df1 df2
P1 P2 P3 P4 P Output
A B C C 1
A B B 2
E F G H H 3
E E 4
I'm trying to merge df2 onto df1 and the output I would like to get would look like我正在尝试将 df2 合并到 df1 上,我想得到的 output 看起来像
df3
P1 P2 P3 P4 Output
A B C NA 1
A B NA NA 2
E F G H 3
E NA NA NA 4
I've tried我试过了
df3<- merge(df1,df2, by.x = "P1", by.y = "P", all.x = T, all.y = T)
df3<- merge(df1,df2, by.x = "P2", by.y = "P", all.x = T, all.y = T)
df3<- merge(df1,df2, by.x = "P3", by.y = "P", all.x = T, all.y = T)
df3<- merge(df1,df2, by.x = "P4", by.y = "P", all.x = T, all.y = T)
however it doesn't work the way I think it should.但是它并没有按照我认为的方式工作。 Is there an easier function that can cleanly merge like this that I am not aware of?
有没有更简单的 function 可以像我不知道的那样干净地合并?
Based on the output showed, it seems that for each row, we need to get the last
non-NA element and do a match
with the second data.frame 'P' column to get the corresponding 'Output'.基于 output 显示,似乎对于每一行,我们需要获取
last
非 NA 元素并与第二个 data.frame 'P' 列进行match
以获得相应的 'Output'。 If that is the logic,如果是这样的逻辑,
df3 <- df1
df3$Output <- apply(df1, 1, function(x)
setNames(df2$Output, df2$P)[tail(x[!is.na(x)], 1)])
Or with tidyverse
或者使用
tidyverse
library(dplyr)
library(tidyr)
df1 %>%
mutate(rn = row_number()) %>%
pivot_longer(cols = -rn, values_drop_na = TRUE) %>%
group_by(rn) %>%
slice(n()) %>%
ungroup %>%
left_join(df2, by = c('value' = 'P')) %>%
select(Output) %>%
bind_cols(df1, .)
df1 <- structure(list(P1 = c("A", "A", "E", "E"), P2 = c("B", "B", "F",
NA), P3 = c("C", NA, "G", NA), P4 = c(NA, NA, "H", NA)), class = "data.frame",
row.names = c(NA,
-4L))
df2 <- structure(list(P = c("C", "B", "H", "E"), Output = 1:4),
class = "data.frame", row.names = c(NA,
-4L))
You can use coalesce
from the dplyr
package to create a new field in df1 which will be the key between the two datasets.您可以使用
dplyr
package 中的coalesce
在 df1 中创建一个新字段,这将是两个数据集之间的键。
library(dplyr)
#create column P, which takes first non null value
df1$P <- coalesce(df1$P4,df1$P3,df1$P2,df1$P1)
#Join data frames on P
df3 <- inner_join(df1, df2, by='P')
#Rmove P from df3
df3$P <- NULL
>> df3
P1 P2 P3 P4 Output
1 A B C <NA> 1
2 A B <NA> <NA> 2
3 E F G H 3
4 E <NA> <NA> <NA> 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.