如何删除R中字符向量中字符串的公共部分?

时间:2017-04-12 11:18:13

标签: r regex string

假设一个字符向量,如下所示

file1_p1_analysed_samples.txt
file1_p1_raw_samples.txt
f2_file2_p1_analysed_samples.txt
f3_file3_p1_raw_samples.txt

期望的输出:

file1_p1_analysed
file1_p1_raw
file2_p1_analysed
file3_p1_raw

我想比较元素并尽可能地从开头和结尾删除字符串的部分,但要保持它们的唯一性。

以上只是一个例子。要移除的部件并非所有元件都通用。我需要一个独立于上例中的字符串的通用解决方案。

到目前为止,我已经能够清除所有元素共有的部分,只要分隔符和生成的分割部分具有相同的长度。这是函数,

mf <- function(x,sep){
    xsplit = strsplit(x,split = sep)
    xdfm <- as.data.frame(do.call(rbind,xsplit))
    res <- list()
    for (i in 1:ncol(xdfm)){
        if (!all(xdfm[,i] == xdfm[1,i])){
            res[[length(res)+1]] <- as.character(xdfm[,i])
        }
    }
    res <- as.data.frame(do.call(rbind,res))
    res <- apply(res,2,function(x) paste(x,collapse="_"))
    return(res)
}

应用上述功能:

 a = c("a_samples.txt","b_samples.txt")
 mf(a,"_")
  V1  V2
 "a" "b"

2

> b = c("apple.fruit.txt","orange.fruit.txt")
> mf(b,sep = "\\.")
      V1       V2
 "apple" "orange"

如果生成的分割部分长度不同,则不起作用。

2 个答案:

答案 0 :(得分:1)

怎么样?
files <- c("file1_p1_analysed_samples.txt", "file1_p1_raw_samples.txt", "f2_file2_p1_analysed_samples.txt", "f3_file3_p1_raw_samples.txt")
new_files <- gsub('_samples\\.txt', '', files)
new_files

......产生

[1] "file1_p1_analysed"    "file1_p1_raw"         "f2_file2_p1_analysed" "f3_file3_p1_raw"     

这会删除字符串中的_samples.txt部分。

答案 1 :(得分:1)

为什么不:

strings <- c("file1_p1_analysed_samples.txt",
"file1_p1_raw_samples.txt",
"f2_file2_p1_analysed_samples.txt",
"f3_file3_p1_raw_samples.txt")

sapply(strings, function(x) {
  pattern <- ".*(file[0-9].*)_samples\\.txt"
  gsub(x, pattern = pattern, replacement = "\\1")
})

()之间匹配的内容可以作为一个组回调,以反向引用。您可以使用\\1执行此操作。您甚至可以指定多个组!

看到你对Jan的答案的评论。为什么不定义静态位并将模式粘贴在一起并始终用括号括起来?然后,您可以随时拨打\\i来替换gsub。

相关问题