【问题标题】:R: Populate a new column in a dataframe based on matching one or several possible stringsR:根据匹配一个或几个可能的字符串填充数据框中的新列
【发布时间】:2023-04-08 06:28:01
【问题描述】:

假设的数据框:

strings      new column
mesh         1
foo          0
bar          0
tack         1
suture       1

如果 df$strings 包含字符串“mesh”、“tack”或“sutur”,我希望新列包含“1”。否则它应该在同一行显示零。我尝试了以下方法:

df$new_column <- ifelse(grepl("mesh" | "tack" | "sutur",
  df$strings, ignore.case = T), "1", "0")

但出现此错误:

Error in "mesh" | "tack" : 
  operations are possible only for numeric, logical or complex types

提前致谢。

【问题讨论】:

    标签: regex r dataframe pattern-matching match


    【解决方案1】:

    您想在grep 中使用单个字符串:

    df$new_column <- ifelse(grepl("mesh|tack|sutur", df$strings, ignore.case = T),
                           "1", "0")
    

    会起作用,但以下会更快:

    df$new_column <- +(grepl("mesh|tack|sutur", df$strings, ignore.case = T))
    

    这将返回一个 0 和 1 整数向量

    【讨论】:

      【解决方案2】:

      我们也可以使用%in%

      df$new_column <-  as.integer(df$strings %in% c("mesh", "tack", "sutur"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-10
        • 2022-01-13
        • 2018-07-10
        • 2016-02-14
        • 1970-01-01
        • 1970-01-01
        • 2021-10-21
        相关资源
        最近更新 更多