Extract a string between patterns/delimiters in R

前端 未结 4 1996
借酒劲吻你
借酒劲吻你 2020-12-11 22:24

I have variable names in the form:

PP_Sample_12.GT

or

PP_Sample-17.GT

I\'m trying to use string split to

相关标签:
4条回答
  • 2020-12-11 22:29

    This grabs the 2nd element of each part of the list that was split and then simplifies it into a vector by subsetting the function [, using sapply to call this function for each element of the original list.

    x <- c('PP_Sample_12.GT', 'PP_Sample-17.GT')
    sapply(strsplit(x, '(?:_(?=\\D)|\\.GT)', perl = T), '[', 2)
    
    [1] "Sample_12" "Sample-17"
    
    0 讨论(0)
  • 2020-12-11 22:38

    Here's a gsub that will extract everything after the first _ and before the last .

    x<-c("PP_Sample-12.GT","PP_Sample-17.GT")
    gsub(".*_(.*)\\..*","\\1", x, perl=T)
    
    0 讨论(0)
  • 2020-12-11 22:50

    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)
    
    0 讨论(0)
  • 2020-12-11 22:54

    If they all start and end with the same characters and those characters aren't anywhere in the middle part of your string, the gsub expression is simple:

    > x <- c("PP_Sample-12.GT","PP_Sample-17.GT")
    > gsub('[(PP_)|(.GT)]','',x)
    [1] "Sample-12" "Sample-17
    
    0 讨论(0)
提交回复
热议问题