I already reviewed the following two posts and think they might answer my question, although I\'m struggling to see how:
1) Conditional replacement of value
You may also use:
df1$B[is.na(df1$B)] <- df2$B[match(df1$A[is.na(df1$B)],df2$A)]
df1
# B C A
# 1 1.7169811 2012-10-01 0
# 2 0.3396226 2012-10-01 5
# 3 4.0000000 2012-10-01 10
# 4 0.1509434 2012-10-01 15
# 5 0.0754717 2012-10-01 20
# 6 20.0000000 2012-10-01 25
# 7 1.7169811 2012-10-01 0
# 8 0.3396226 2012-10-01 5
# 9 5.0000000 2012-10-01 10
# 10 5.0000000 2012-10-01 15
Try the following code which takes your original statement and makes a small tweak in the TRUE
argument of the ifelse
function:
> df1$B <- ifelse(is.na(df1$B) == TRUE, df2$B[df2$A %in% df1$A], df1$B)
# Switched '==' to '%in%' ---^
> df1
B C A
1 1.7169811 2012-10-01 0
2 0.3396226 2012-10-01 5
3 4.0000000 2012-10-01 10
4 0.1509434 2012-10-01 15
5 0.0754717 2012-10-01 20
6 20.0000000 2012-10-01 25
7 1.7169811 2012-10-01 0
8 0.3396226 2012-10-01 5
9 5.0000000 2012-10-01 10
10 5.0000000 2012-10-01 15
df1[is.na(df1$B), c('A','C','B')] <- merge(df1[is.na(df1$B), -1], df2, by = 'A')