Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

regex - Extract a string between patterns/delimiters in R

I have variable names in the form:

PP_Sample_12.GT

or

PP_Sample-17.GT

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]))

I end up with Sample for PP_Sample_12.GT.

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using this input:

x <- c("PP_Sample_12.GT", "PP_Sample-17.GT")

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 Replace the prefix (^[^_]*_) and the suffix (\.[^.]*$") with the empty string:

gsub("^[^_]*_|\.[^.]*$", "", x)

3) gsubfn::strapplyc extract everything between underscore and dot.

library(gsubfn)
strapplyc(x, "_(.*)\.", simplify = TRUE)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...