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
  • 463
  • 4
  • 11

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,048
  • 8
  • 19
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
  • 377,200
  • 20
  • 156
  • 213
0

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

v[which(v!="S" & v!="D")]<-"x"
bricx
  • 593
  • 4
  • 18