user2300940
user2300940

Reputation: 2385

split paired samples based on substring

I have two groups of paired samples that could be separated by the first two letters. I would like to make two groups based on the pairing using something like [tn][abc].

Example of paired samples:
nb-008  ta-008
na015   ta-015

data:

    > colnames(data)
      "nb-008"  "nb-014"  "na015"   "na-018"  "ta-008"   "tc-014"  "ta-015"  "ta-018"  

  patient <- factor(sapply(str_split(colnames(data), '[tn][abc]'), function(x) x[[1]]))

Upvotes: 2

Views: 64

Answers (1)

akrun
akrun

Reputation: 887108

We can create a grouping variable with sub. We match the pattern of 2 characters (..) from the beginning of the string (^) followed by - (if present), followed by one or more characters (.*) that we capture as a group (inside the brackets), and replace by the backreference (\\1). This can be used to split the column names.

split(colnames(data), sub('^..-?(.*)', '\\1', colnames(data))))
#$`008`
#[1] "nb-008" "ta-008"

#$`014`
#[1] "nb-014" "tc-014"

#$`015`
#[1] "na015"  "ta-015"

#$`018`
#[1] "na-018" "ta-018"

data

 v1 <- c("nb-008",  "nb-014",  "na015",   "na-018",  
            "ta-008",   "tc-014",  "ta-015", "ta-018" ) 
set.seed(24)
data <- setNames(as.data.frame(matrix(sample(0:8, 8*5, 
               replace=TRUE), ncol=8)), v1)

Upvotes: 1

Related Questions