Say I have the following dataframes:
DF1 <- data.frame("A" = rep(c("A","B"), 18),
"B" = rep(c("C","D","E"), 12),
"NUM"= rep(rnorm(36,10,1)),
"TEST" = rep(NA,36))
DF2 <- data.frame("A" = rep("A",6),
"B" = rep(c("C","D"),6),
"VAL" = rep(c(1,3),3))
*Note: Each unique combination of variables A
and B
in DF2
should have a unique VAL
.
For each row, I would like to replace the NA
in TEST
with the corresponding value of VAL
in DF1
if the values in columns A
and A
match and the values in columns B
and B
match for that row. Otherwise, I'd leave TEST
as NA
. How would I do this without looping through each combination using match?
Ideally, an answer would scale to two data frames with many columns to match upon.
DF2
should have a uniqueVAL
. I need to figure out a way to encode that in the example. – DomingadomingoDF2 <- data.frame(A=rep('A',2), B=c('C', 'D'), VAL=rnorm(2))
andmerge
will get the resultmerge(DF1, DF2, all=TRUE)
– HaileeVAL
should be chosen for a given combination ofA
andB
since there are multiple. – HydrocelluloseDF2
so I think that there is only one possible option forVAL
for each row inDF1
. I guessDF2
could be reduced to only the unique combinations of the predictors. – Domingadomingo