Reputation: 463
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")
Upvotes: 0
Views: 40
Reputation: 388982
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')
Upvotes: 1
Reputation: 1080
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"
Upvotes: 2
Reputation: 663
I believe that the which
statement is what you are looking for:
v[which(v!="S" & v!="D")]<-"x"
Upvotes: 0