r - 如何删除 R 中字符向量中字符串的公共(public)部分?

标签 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"

如果生成的拆分部分长度不同,则此方法无效。

最佳答案

怎么样

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 部分。

关于r - 如何删除 R 中字符向量中字符串的公共(public)部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43368073/

相关文章:

R 使用 apply() 或 lapply() 等加速 for 循环

regex - Powershell:如果正则表达式不匹配,则保留项目

javascript - 使用javascript从字符串中删除 "Form"标签及其内容

java - 用零填充字符串的更好方法

C 将字符一一追加到字符数组中

r - 顺序神经网络

r - ggplot2 geom_bar 在某些情况下在位置 ="fill"时给出错误

r - 如何在 ggplot2 中绘制一组旋转密度?

Python 代码使用正则表达式来确保字符串是字母数字加 . - _

swift - 如何屏蔽字符串以仅显示最后 3 个字符?