假设一个字符向量如下所示
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/