I have a vector v. I would like to replace everything that doesn't equal S or D. It can be replaced by x.
v <- c("S","D","hxbasxhas","S","cbsdc")
result
r <- c("S","D","x","S","x")
A stringr approach is possible with a negative look-around.
Using str_replace:
library(stringr)
str_replace(v, "^((?!S|D).)*$", "x")
Result:
[1] "S" "D" "x" "S" "x"
 
    
    You can negate %in% :
v <- c("S","D","hxbasxhas","S","cbsdc")
v[!v %in% c('S', 'D')] <- 'x'
v
#[1] "S" "D" "x" "S" "x"
Or use forcats::fct_other :
forcats::fct_other(v, c('S', 'D'), other_level = 'x')
 
    
    I believe that the which statement is what you are looking for:
v[which(v!="S" & v!="D")]<-"x"
