updating column in one dataframe with value from another dataframe based on matching values
you don't need z$color
in the first place if its just place holder, you can replace NA
later with 0
z$color<-y[match(z$letter, y$letter),2]
You can use merge
:
dat <- merge(z, y, by = "letter", all.x = TRUE)
transform(dat, color = ifelse(is.na(color.y),
color.x, as.character(color.y)))[-(2:3)]
letter color
1 a red
2 a red
3 a red
4 b blue
5 b blue
6 b blue
7 b blue
8 c green
9 c green
10 c green
11 c green
12 c green
13 d 0
14 d 0
15 d 0
16 d 0
17 e 0
18 e 0
19 e 0
20 e 0
sqldf/sqlite is very flexible:
library(sqldf)
z$color="0" # to avoid conflicts numeric/characters
z <- sqldf(c("UPDATE z
SET color = (SELECT y.color
FROM y
WHERE z.letter = y.letter
)
WHERE EXISTS (SELECT 1
FROM y
WHERE z.letter = y.letter
)"
, "select * from main.z"
)
)
z
letter color
1 b blue
2 a red
3 d 0.0
4 d 0.0
5 e 0.0
6 a red
7 a red
8 c green
9 b blue
10 c green
11 e 0.0
12 c green
13 b blue
14 d 0.0
15 d 0.0
16 d 0.0
17 c green
18 e 0.0
19 a red
20 c green