Starting from a dataframe like this:
col1 <- c("Anne", "Emma", "Katy", "Albert", "Richard")
col2 <- c("Albert", "Mark", "Mike", "Loren", "Anne")
col3 <- c("Mark", "Emma", "Paul", "George", "Samuel" )
df <- cbind(col1, col2, col3)
I would like to keep only the values reported in this vector:
selected <- c("Emma", "Katy", "Mark")
and delete all the others, in order to have a new dataframe like this:
col1 col2 col3
NA NA "Mark"
"Emma" "Mark" "Emma"
"Katy" NA NA
NA NA NA
NA NA NA
I have tried with the following code and it works:
df[df != "Emma" & df != "Katy" & df != "Mark"] <- NA
but I would like to find a way to use the vector selected in an if statement, instead of writing all the conditions manually.
Indeed, my actual dataframe and vector of values are bigger than the ones in this example.
Thanks in advance for your help!