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
)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With