【问题标题】:conditional str_replace based on matching regex within mutate?基于变异中匹配正则表达式的条件str_replace?
【发布时间】:2019-09-20 14:47:31
【问题描述】:

对于“区”列中与regex("[:alpha:]{2}AL") 匹配的任何条目,我想将“AL”替换为“01”。

例如:

df <- tibble(district = c("NY14", "MT01", "MTAL", "PA10", "KS02", "NDAL", "ND01", "AL02", "AL01"))

我试过了:

  df %>% mutate(district=replace(district, 
                          str_detect(district, regex("[:alpha:]{2}AL")), 
                          str_replace(district,"AL","01"))) 

和

  df %>% mutate(district=replace(district, 
                          str_detect(district, regex("[:alpha:]{2}AL")), 
                          paste(str_sub(district, start = 1, end = 2),"01",sep = "")) 

但存在矢量化问题。

【问题讨论】:

    标签: r regex dplyr stringr


    【解决方案1】:

    这样好吗?

    str_replace_all(string=df$district,
                    pattern="(\\w{2})AL",
                    replacement="\\101")
    

    我将正则表达式替换为\\w,一个单词字符:https://www.regular-expressions.info/shorthand.html

    我使用\\1 表示将字符串替换为第一个捕获的区域,该区域在(\\w{2}) 中捕获,因此保留前2 个字母,然后添加01

    【讨论】:

    【解决方案2】:

    您可以将replace 更改为ifelse

    ifelse( str_detect(df$district, regex("[:alpha:]{2}AL")), 
             str_replace(df$district,"AL","01"),df$district)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      相关资源
      最近更新 更多