giegie
giegie

Reputation: 463

Replace a value in a vector if doesn't equal to two conditions (in R)

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

Answers (3)

Ronak Shah
Ronak Shah

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

Ali
Ali

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

bricx
bricx

Reputation: 663

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

v[which(v!="S" & v!="D")]<-"x"

Upvotes: 0

Related Questions