I have the following code:
set.seed(47)
df <- data.frame(V1 = sample(letters[1:5], size = 10, replace = TRUE),
V2 = 101:110)
partial_key <- data.frame(V1 = letters[1:3], V2 = 1:3)
> df
V1 V2
1 e 101
2 b 102
3 d 103
4 e 104
5 c 105
6 d 106
7 b 107
8 c 108
9 c 109
10 e 110
> partial_key
V1 V2
1 a 1
2 b 2
3 c 3
I’d like to replace the values of V2 in df with the corresponding values from partial_key that match in the V1 columns. The non-matches should remain as is.
With a complete key, I’d use match, which replaces the correct values, but replaces the non-matches with NA.
df[, "V2"] <- partial_key[match(df$V1, partial_key$V1), "V2"]
## Replaces too much
I can hack together a solution with %in%, but is there a better way? Something more intuitive, with less typing?
df[df$V1 %in% partial_key$V1, "V2"] <-
partial_key[match(df$V1[df$V1 %in% partial_key$V1], partial_key$V1), "V2"]
## Works, but is there a better way?
> df
V1 V2
1 e 101
2 b 2
3 d 103
4 e 104
5 c 3
6 d 106
7 b 2
8 c 3
9 c 3
10 e 110
Using
%in%is unnecessary since the output ofmatchalready contains that info. So you can do something like this:Sometimes I wish R had a base
if.nafunction similar to Excel’sIFERROR. I have it in my Rprofile: