使用R

时间:2017-11-28 22:11:59

标签: r regex gsub

我试图在一个大型列表中重命名给我的一些字符串。问题是我只需要替换一些不是全部的字符。

exdata <- c("i_am_having_trouble_with_this_string",
            "i_am_wishing_files_were_cleaner_for_me",
            "any_help_would_be_greatly_appreciated")

从这个列表中,我想替换&#34; _&#34;的第三个到第五个实例。与&#34; - &#34;。我无法理解正则表达式编码,因为大多数示例都将字符串拆分而不是保持完整。

2 个答案:

答案 0 :(得分:2)

以下是一些替代方法。通过将3和5替换为其他数字,可以将它们全部推广到任意边界。

1)strsplit 在下划线处拆分字符串并使用paste使用适当的分隔符将其折叠回来。没有包使用。

i <- 3
j <- 5
sapply(strsplit(exdata, "_"), function(x) {
  g <- seq_along(x)
  g[g < i] <- i
  g[g > j + 1] <- j+1
  paste(tapply(x, g, paste, collapse = "_"), collapse = "-")
})

,并提供:

[1] "i_am_having-trouble-with-this_string"  
[2] "i_am_wishing-files-were-cleaner_for_me"
[3] "any_help_would-be-greatly-appreciated" 

2)for循环这会将old中{j} new的前j次转换为x,然后翻译new的第一次i-1次出现1}}回到old。没有包使用。

translate <- function(old, new, x, i = 1, j) {
 if (i <= 1) {
    if (j > 0) for(k in seq_len(j)) x <- sub(old, new, x, fixed = TRUE)
    x
 } else Recall(new, old, Recall(old, new, x, 1, j), 1, i-1)
}

translate("_", "-", exdata, 3, 5)

,并提供:

[1] "i_am_having-trouble-with-this_string"  
[2] "i_am_wishing-files-were-cleaner_for_me"
[3] "any_help_would-be-greatly-appreciated" 

3)gsubfn 这使用了一个包但反过来要比其他包短得多。 gsubfngsub类似,只是gsub中的替换字符串可以是字符串,列表,函数或原型对象。对于proto对象,每次与正则表达式匹配时,都会调用proto对象的fun方法。匹配字符串下方作为fun传递给x,而fun的输出替换数据中的匹配。 proto对象会自动填充由gsubfn设置的多个变量,并由fun访问,包括count,第一个匹配为1,第二个匹配为2,依此类推。有关详细信息,请参阅gsubfn vignette - 第4节讨论原型对象的使用。

library(gsubfn)

p <- proto(i = 3, j = 5, 
      fun = function(this, x) if (count >= i && count <= j) "-" else x)
gsubfn("_", p, exdata)

,并提供:

[1] "i_am_having-trouble-with-this_string"  
[2] "i_am_wishing-files-were-cleaner_for_me"
[3] "any_help_would-be-greatly-appreciated" 

答案 1 :(得分:1)

> gsub('(.*_.*_.*?)_(.*?)_(.*?)_(.*)','\\1-\\2-\\3-\\4', exdata)
[1] "i_am_having-trouble-with-this_string"   "i_am_wishing-files-were-cleaner_for_me" "any_help_would-be-greatly-appreciated"
相关问题