【问题标题】:Insert dots around substring using gsub in R在 R 中使用 gsub 在子字符串周围插入点
【发布时间】:2014-01-04 19:21:04
【问题描述】:

我想在 R 中有一个函数,如果它们不存在,则在给定的子字符串(例如“alpha”)周围插入点(“.”)。例如。 string="10-alpha-epoxy-Amorph-4-ene" 应该返回

"10-.alpha.-epoxy-Amorph-4-ene"

string="alpha-cadolene" 应该返回

".alpha.-cadolene"

但是 string=".alpha.-cadolene" 应该返回

".alpha.-cadolene"

(子字符串可能出现多次)

在 R 中使用 gsub 完成此任务的最简单方法是什么?

干杯,汤姆

【问题讨论】:

    标签: r gsub string-substitution


    【解决方案1】:

    我会做这样的事情:

    gsub("[.]?(alpha)[.]?", ".\\1.", c("10-alpha-epoxy-Amorph-4-ene",
                                   ".alpha.-cadolene", "alpha.-cadolene",
                                    ".alpha-cadolene"                              
                                     ))
    [1] "10-.alpha.-epoxy-Amorph-4-ene" ".alpha.-cadolene"             
        ".alpha.-cadolene"              ".alpha.-cadolene"  
    

    编辑概括为许多术语:

    如果您有术语列表,您可以使用 paste 来使用 create tour 正则表达式:

    terms <- c('alpha','gamma','beta','delta')
    
    gsub(paste0("[.]?(",paste0(terms,collapse='|'),")[.]?"), ".\\1.", 
                    c("10-alpha-epoxy-Amorph-4-ene",
                     ".gamma.-cadolene", "beta.-cadolene",
                     ".delta-cadolene")) 
    
    [1] "10-.alpha.-epoxy-Amorph-4-ene" ".gamma.-cadolene"             
        ".beta.-cadolene"              
    [4] ".delta.-cadolene"  
    

    EDIT获取完整的greels列表:

    library(XML)
    dat <- readHTMLTable("http://en.wikipedia.org/wiki/Greek_alphabet",
                         strinsAsFactors=FALSE)[[2]]
    
    terms <- as.character(dat$V2[-c(1,2)])
     [1] "alpha"   "beta"    "gamma"   "delta"   "epsilon" "zeta"    "eta"     "theta"   "iota"    "kappa"   "lambda" 
    [12] "mu"      "Name"    "Modern"  "nu"      "xi"      "omicron" "pi"      "rho"     "sigma"   "tau"     "upsilon"
    [23] "phi"     "chi"     "psi"     "omega"  
    

    【讨论】:

    • 它是否也可以概括,以便您可以为匹配 alpha、beta、gamma、delta 等执行此操作?还是需要单独的 gsub 命令?
    • 你的意思是所有的希腊人吗?
    • 是的,所有的希腊人都是完美的!但我不知道是否有一些标准可以识别所有完整拼写的希腊字母......(事实上,我仍在寻找一些命令来将 UTF-8 希腊字符转换为完整拼写的字母拉丁语,反之亦然 - 现在我用一系列替换手动完成此操作)
    【解决方案2】:

    这是一种方法:

    R> gsub("-(alpha)-", ".-\\1-.", "10-.alpha.-epoxy-Amorph-4-ene")
    [1] "10-.alpha.-epoxy-Amorph-4-ene"
    R> gsub("-(alpha)-", ".-\\1-.", "10-alpha-epoxy-Amorph-4-ene")
    [1] "10.-alpha-.epoxy-Amorph-4-ene"
    R> 
    

    (....) 表达式被保留,便于在替换部分中将其召回为\\1(其中第二个这样的表达式将是\\2)。

    但明确命名表达式,您要确保不会发生其他匹配。你当然可以概括一下:

    gsub("-([a-z]*)-", ".-\\1-.", "10-.alpha.-epoxy-Amorph-4-ene")
    

    将替换小写字母的任何表达式(但不包括标点符号、数字...)。

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 2021-01-28
      • 2021-12-18
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 2016-11-08
      • 2015-07-06
      相关资源
      最近更新 更多