Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 -

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading