How to create a column with more than one logical argument

Hello, i'm trying to create a new column based on a logical order. What i need to do is:
Create a column "d", and their values will be: "1" if the columns "x", "y", or "z" has a number 1, if it isn't the value will be 0

x y z d
1 na 2 1
1 1 2 1
na 2 2 0
1 2 na 1
na 1 1 1
1 2 2 1
2 2 1 1
2 na na 0

This seems like a good time to use the case_when() function in dplyr:

library(dplyr)

data %>%
  mutate(d = case_when(
    x==1 ~ 1,
    y==1 ~ 1,
    z==1 ~ 1,
    TRUE ~ 0
  )
)
1 Like

While dplyr::case_when() does the trick, and does it nicely, a simple ifelse() with an OR clause might be preferable in some use cases.

Consider this base R approach also:

data$result <- ifelse(data$x == 1 | data$y == 1 | data$z == 1, 1, 0)
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.