Home > Software engineering >  Extract a part of string and join to the start
Extract a part of string and join to the start

Time:10-14

I have a list

temp_list <- c("Temp01_T1", "Temp03_T1", "Temp04_T1", "Temp11_T6", 
"Temp121_T6", "Temp99_T8")

I want to change this list as follows

output_list <- c("T1_Temp01", "T1_Temp03", "T1_Temp04", "T6_Temp11", 
    "T6_Temp121", "T8_Temp99")

Any leads would be appreciated

CodePudding user response:

Base R answer using sub -

sub('(\\w )_(\\w )', '\\2_\\1', temp_list)
#[1] "T1_Temp01"  "T1_Temp03"  "T1_Temp04"  "T6_Temp11"  "T6_Temp121" "T8_Temp99"

You can capture the data in two capture groups, one before underscore and another one after the underscore and reverse them using backreference.

CodePudding user response:

This should work.

sub("(.*)(_)(.*)", "\\3\\2\\1", temp_list)

You capture the three groups, one before the underscore, one is the underscore and one after and then you rearrange the order in the replacement expression.

CodePudding user response:

python approach: splitting on '_', reversing order with -1 step index slicing, and joining with '_':

['_'.join(i.split('_')[::-1]) for i in temp_list]

CodePudding user response:

You can use str_split() from stringr and then use sapply() to paste it in the order you want if it is always seperated by a _

x <- stringr::str_split(temp_list, "_")
sapply(x, function(x){paste(x[[2]],x[[1]],sep = "_")})

CodePudding user response:

A trick with paste read.table

> do.call(paste, c(rev(read.table(text = temp_list, sep = "_")), sep = "_"))
[1] "T1_Temp01"  "T1_Temp03"  "T1_Temp04"  "T6_Temp11"  "T6_Temp121"
[6] "T8_Temp99"
  • Related