0

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")
giegie
  • 391
  • 3
  • 10

3 Answers3

2

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"
Ali
  • 1,016
  • 7
  • 17
1

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')
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
0

I believe that the which statement is what you are looking for:

v[which(v!="S" & v!="D")]<-"x"
bricx
  • 563
  • 3
  • 16