在 R 中的模式/分隔符之间提取字符串 [英] Extract a string between patterns/delimiters in R
问题描述
我有以下形式的变量名:
I have variable names in the form:
PP_Sample_12.GT
或
PP_Sample-17.GT
我正在尝试使用字符串拆分来提取中间部分:即 Sample_12
或 Sample-17
.但是,当我这样做时:
I'm trying to use string split to grep out the middle section: ie Sample_12
or Sample-17
. However, when I do:
IDtmp <- sapply(strsplit(names(df[c(1:13)]),'_'),function(x) x[2])
IDs <- data.frame(sapply(strsplit(IDtmp,'.GT',fixed=T),function(x) x[1]))
我最终得到了 PP_Sample_12.GT
的 Sample
.
I end up with Sample
for PP_Sample_12.GT
.
还有其他方法可以做到这一点吗?也许使用模式/替换功能?虽然,不确定这是否存在于 R(但我认为这可能适用于 gsub
)
Is there another way to do this? Maybe using a pattern/replace kind of function ? Though, not sure if this exists in R (but I think this might work with gsub
)
推荐答案
使用此输入:
x <- c("PP_Sample_12.GT", "PP_Sample-17.GT")
1) strsplit.用点替换第一个下划线,然后在点上拆分:
1) strsplit. Replace the first underscore with a dot and then split on dots:
spl <- strsplit(sub("_", ".", x), ".", fixed = TRUE)
sapply(spl, "[", 2)
2) gsub 替换前缀 (^[^_]*_
) 和后缀 (\\.[^.]*$"
) 与空字符串:
2) gsub Replace the prefix (^[^_]*_
) and the suffix (\\.[^.]*$"
) with the empty string:
gsub("^[^_]*_|\\.[^.]*$", "", x)
3) gsubfn::strapplyc 提取下划线和点之间的所有内容.
3) gsubfn::strapplyc extract everything between underscore and dot.
library(gsubfn)
strapplyc(x, "_(.*)\\.", simplify = TRUE)
这篇关于在 R 中的模式/分隔符之间提取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!