R. Buchanan R. Buchanan - 2 months ago 8
R Question

Adding NA's to specific portions of a replacement

I'm working with two vectors and a data frame:

x <- c("A", "B", "D")
y <- c(1, 3, 5)

df:
# var1 var2
#1 ddAd NA
#2 dBdd NA
#3 ddCd NA
#4 Dddd NA


The result I'm going for is this:

df:
# var1 var2
#1 ddAd 1
#2 dBdd 3
#3 ddCd NA
#4 Dddd 5


Someone suggested the following approach:

z <- grep(paste(x, collapse="|"), df$var1, value = FALSE)
df$var2 <- y[z]


The problem I'm having with the the above approach is that my replacement has fewer lines than the data frame. Is there an easy way to add NA's to the replacement so that they correspond to rows that don't have an "A", "B" or "D"?

Answer

We can use the index in 'z' to subset the 'var2' on the lhs of <

df$var2[z] <- y