Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a string between patterns/delimiters in R

Tags:

regex

r

strsplit

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)

like image 710
user2726449 Avatar asked Jan 11 '23 15:01

user2726449


1 Answers

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)
like image 160
G. Grothendieck Avatar answered Jan 18 '23 23:01

G. Grothendieck