0

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

vector==c(1,3,5)

But this does not give me the correct output.

megmac
  • 547
  • 2
  • 11
  • (You can still accept the answer once the interface allows you, but the dupe link is preferred. Thanks!) – r2evans Dec 29 '21 at 17:15

1 Answers1

3

Use the %in% operator.

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

In your case,

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

rg255
  • 4,119
  • 3
  • 22
  • 40