ifelse statement with multiple conditions

I am familiar with writing ifelse() statements and they are very useful, but when they have multiple conditions they appear to be very inefficient. I am curious if there is a more efficient way to write them. For example, if I had the following dataframe

test <- data.frame(col = c("a", "b", "c", "d", "e"))
test$col <- factor(test$col)

  col
1   a
2   b
3   c
4   d
5   e

I could write

test$col2 <- ifelse(test$col == "a" | test$col == "b" | test$col == "c", "x", "z")
test

  col col2
1   a    x
2   b    x
3   c    x
4   d    z
5   e    z

Here I have essentially written the same thing (test$col ==) three times within the one ifelse() statement. How can I write the code such that I am only typing test$col == once?

I appreciate that the below is incorrect and does not work, but my guess at something like this would be

test$col2 <- ifelse(test$col == c("a", "b", "c"), "x", "z")

OR

test$col2 <- ifelse(test$col == "a" | "b" | "c", "x", "z")

It is inefficient to be writing the code test$col == multiple times. Can this be avoided in such an ifelse() statement?

  • 1

    test$col %in% c("a", "b", "c")

    – 

  • @zephryl This is not correct, or at least ambiguous. Wrote an answer on that below, why.

    – 

Leave a Comment