根据R中其他列的多个条件创建一个新列

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

我有一个具有这种结构的数据框:

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

如果 col1col2 都不是 0 而不是 2,我如何创建另一个显示 1 的列?

谢谢!

使用 case_when dplyr 来解决就像:

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