'Create a new column based on multiple conditions in other columns in R

I have a data frame that has this structure:

dat <- data.frame(col1 = sample(0:3, 10, replace = TRUE),
                  col2 = sample(0:3, 10, replace = TRUE))

How can I create another column that says 1 if both col1 and col2 are not 0 and 2 otherwise?

Thank you!



Solution 1:[1]

using case_when dplyr to solve would be like:

dat %>%
  mutate(col3 = case_when(
    col1 != 0 & col2 != 0 ~ 1,
    TRUE ~ 2
  ))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lucca Nielsen