【问题标题】:Replace entire strings based on partial match根据部分匹配替换整个字符串
【发布时间】:2014-03-15 02:38:46
【问题描述】:

R 新手。如果存在部分匹配,则希望替换整个字符串。

d = c("SDS0G2 Blue", "Blue SSC2CWA3", "Blue SA2M1GC", "SA5 Blue CSQ5")

gsub("Blue", "Red", d, ignore.case = FALSE, fixed = FALSE)

输出:“SDS0G2红色”“红色SSC2CWA3”“红色SA2M1GC”“SA5红色CSQ5”

所需输出:“红色”“红色”“红色”“红色”

非常感谢任何帮助解决这个问题。

【问题讨论】:

    标签: regex r


    【解决方案1】:

    我建议使用grepl 来查找索引并将这些索引替换为“Red”:

    d = c("SDS0G2 Blue", "Blue SSC2CWA3", "Blue SA2M1GC", "SA5 Blue CSQ5", "ABCDE")
    d[grepl("Blue", d, ignore.case=FALSE)] <- "Red"
    d
    # [1] "Red"   "Red"   "Red"   "Red"   "ABCDE"
    

    【讨论】:

      【解决方案2】:

      如果您确实想将变量保留为一个因素并一次替换多个部分匹配项,则以下函数将起作用(来自另一个问题的示例)。

      
      clrs <- c("blue", "light blue", "red", "rose", "ruby", "yellow", "green", "black", "brown", "royal blue")
      dfx <- data.frame(colors1=clrs, colors2 = clrs, Amount=sample(100,10))
      
      # Function to replace levels with regex matching
      make_levels <- function(.f, patterns, replacement = NULL, ignore.case = FALSE) {
      
        lvls <- levels(.f)
      
        # Replacements can be listed in the replacement argument, taken as names in patterns, or the patterns themselves.
        if(is.null(replacement)) {
          if(is.null(names(patterns)))
            replacement <- patterns
          else
            replacement <- names(patterns)
        }
      
        # Find matching levels
        lvl_match <- setNames(vector("list", length = length(patterns)), replacement)
        for(i in seq_along(patterns))
          lvl_match[[replacement[i]]] <- grep(patterns[i], lvls, ignore.case = ignore.case, value = TRUE)
      
        # Append other non-matching levels
        lvl_other <- setdiff(lvls, unlist(lvl_match))
        lvl_all <- append(
          lvl_match, 
          setNames(as.list(lvl_other), lvl_other)
        )
      
        return(lvl_all)
      
      }
      
      # Replace levels
      levels(dfx$colors2) <- make_levels(.f = dfx$colors2, patterns = c(Blue = "blue", Red = "red|rose|ruby"))
      
      dfx
      #>       colors1 colors2 Amount
      #> 1        blue    Blue     75
      #> 2  light blue    Blue     55
      #> 3         red     Red     47
      #> 4        rose     Red     83
      #> 5        ruby     Red     56
      #> 6      yellow  yellow     10
      #> 7       green   green     25
      #> 8       black   black     29
      #> 9       brown   brown     23
      #> 10 royal blue    Blue     24
      

      由reprex package (v0.3.0) 于 2020-04-18 创建

      【讨论】:

        猜你喜欢
        • 2019-10-08
        • 2019-01-30
        • 2020-09-27
        • 1970-01-01
        • 2019-12-10
        • 2020-09-23
        • 1970-01-01
        • 2014-03-22
        • 2023-02-16
        相关资源
        最近更新 更多