Home > database >  Create a new column based on multiple conditions in other columns in R
Create a new column based on multiple conditions in other columns in R

Time:05-15

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!

CodePudding user response:

using case_when dplyr to solve would be like:

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