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

How to simplify code in ifelse statment in R

Seems trivial but to clean up my code I would like to know if there is a way to consolidate my == arguments in a ifelse function

For Example:

vector = c(1,3,5,8,5,2,3,4,5,6,5,0,7,8,9)
new_vector <- ifelse(((vector==1)|(vector==3)|(vector==5)),"A","B")

Is there a way to combine the 1,3, and 5 into one argument? I tried

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

vector==c(1,3,5)

But this does not give me the correct output.

>Solution :

Use the %in% operator.

vector %in% c(1,3,5)

In your case,

new_vector <- ifelse(vector %in% c(1,3,5), "A", "B")

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