【问题标题】:grepl in multiple columns in RR中多列中的grepl
【发布时间】:2019-12-10 17:33:00
【问题描述】:

我正在尝试跨 R 中的多个列进行字符串搜索和替换。我的代码:

# Get columns of interest
selected_columns <- c(368,370,372,374,376,378,380,382,384,386,388,390,392,394)

#Perform grepl across multiple columns
df[,selected_columns][grepl('apples',df[,selected_columns],ignore.case = TRUE)] <- 'category1'

但是,我收到了错误:

Error: undefined columns selected

提前致谢。

【问题讨论】:

    标签: r grepl


    【解决方案1】:

    grep/grepl 适用于向量/矩阵,而不适用于 data.frame/list. According to the?grep`

    x - 寻找匹配的字符向量,或者可以被 as.character 强制转换为字符向量的对象。

    我们可以循环遍历列 (lapply) 和 replace 基于匹配的值

    df[, selected_columns] <- lapply(df[, selected_columns],
         function(x) replace(x, grepl('apples', x, ignore.case = TRUE), 'category1'))
    

    或者dplyr

    library(dplyr)
    library(stringr)
    df %>%
         mutate_at(selected_columns, ~ replace(., str_detect(., 'apples'), 'category1'))
    

    【讨论】:

    • 谢谢,你能解释一下这行代码是做什么的吗:function(x) replace(x, grepl('apples', x, ignore.case = TRUE), 'category1'))
    • @DiamondJoe12 function(x) 是动态创建的 lambda 函数或匿名函数,因此,这里的 x 将每个列值引用为 replace 所在的向量用于更改存在“苹果”的值
    • 谢谢!还有一个问题,如果我不仅想用“category1”替换“apples”,还想用“apples”和“oranges”替换,我可以这样做:function(x) replace(x, grepl('apples', '橙子', x, ignore.case = TRUE), 'category1'))
    • 我认为这可行:function(x) replace(x, grepl('apples|oranges', x, ignore.case = TRUE), 'category1'))
    • @DiamondJoe12 在这种情况下使用grepl("apples|oranges", x, ..
    【解决方案2】:

    假设您想部分匹配一个单元格并替换它,您可以使用rapply() 并使用gsub() 将具有"apples" 的单元格内容替换为"category1":

    df[selected_columns] <- rapply(df[selected_columns], function(x) gsub("apples", "category1", x), how = "replace")
    

    在搜索字符串时,请记住 grepl()/gsub()(在您的正则表达式中有边界和没有边界)和 %in%/match() 之间的区别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 2020-08-14
      相关资源
      最近更新 更多