Johan
Johan

Reputation: 109

rename a vector in reverse in r

I would like to rename the rest of the variables that do not match my vector, but I do not know what the appropriate code would be, I add an example.

example<-c("a","b","c","d","e")
keep<-c("b","c","d")
example[example %in% -keep] <- "vocal"

Upvotes: 1

Views: 58

Answers (1)

akrun
akrun

Reputation: 887291

Negate (!) instead of - to reverse the logical output i.e. TRUE -> FALSE and viceversa

example[!example %in% keep] <- "vocal"

If we want to use -, wrap with which to get the position index and then use

example[-which(example %in% keep)] <- "vocal"

but this is buggy and can have unexpected output in certain cases. e.g. if there are no matches

> keep1 <- c("f", "l")
> which(example %in% keep1)
integer(0)
> -which(example %in% keep1)
integer(0)
> example[-which(example %in% keep1)] <- "vocal"
> example
[1] "a" "b" "c" "d" "e"

Here, none of them is changed because the which returned no elements, which had no impact with -

Upvotes: 1

Related Questions