【问题标题】:Cant use mutate() with multiple conditions from same column with dplyr [duplicate]不能使用 mutate() 与来自同一列的多个条件与 dplyr [重复]
【发布时间】:2020-07-21 23:20:51
【问题描述】:

我想在 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 和逻辑运算符的经验

我该怎么办?

谢谢

【问题讨论】:

    标签: r logical-operators dplyr


    【解决方案1】:

    我们可以使用%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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      相关资源
      最近更新 更多