user4665665 user4665665 - 17 days ago 6
R Question

how to replace specific values in data frame to NA in R?

I am working with a data frame in R and I want to replace the values of certain id to NA. Here is an example of the input file.

id y
222 12
432 23
522 22
443 11


And here is my desired output:

id y
222 12
432 NA
522 22
443 NA

Answer
idsToBeReplaced <- c(432, 443)    
df[df$id %in% idsToBeReplaced, "y"] <- NA

#  id  y
#1 222 12
#2 432 NA
#3 522 22
#4 443 NA