不能将 mutate() 与 dplyr 的同一列中的多个条件一起使用

Cant use mutate() with multiple conditions from same column with dplyr

我想在 tibble(data) 中使用 mutate() 创建一个新列 (newcol)。新列 (newcol) 中的值取决于另一列 (othercol) 中的值。

unique(data$othercol)
[1] "1"  "A"  "A1" "A3" "B"  "B2" "C2" "D"  "E"  "F"  "G" 

如果othercol是"A"、"A1"、"A3",我想在newcol中翻译成1,否则newcol应该是0。

我尝试了几个代码但都失败了。这可能都归结为我缺乏 dplyr 和逻辑运算符的经验

我该怎么办?

谢谢

我们可以使用%in%创建一个逻辑向量

library(dplyr)
data <- data %>%
           mutate(newcol = as.integer(othercol %in% c('A', 'A1', 'A3')))

或使用ifelse

data <- data %>%
           mutate(newcol = ifelse(othercol %in% c('A', 'A1', 'A3'), 1, 0))

或使用str_detect

library(stringr)
data <- data %>%
           mutate(newcol = +(str_detect(othercol, '^A\d*$')))

或使用grepl

data$newcol <- +(grepl("^A\d*$", data$othercol))