Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split and expand the (vector) at the delimiter: R

Tags:

r

I have this vector (it's big in size) myvec. I need to split them matching at / and create another result vector resvector. How can I get this done in R?

myvec<-c("IID:WE:G12D/V/A","GH:SQ:p.R172W/G", "HH:WG:p.S122F/H")

resvector

IID:WE:G12D, IID:WE:G12V,IID:WE:G12A,GH:SQ:p.R172W,GH:SQ:p.R172G,HH:WG:p.S122F,HH:WG:p.S122H
like image 312
MAPK Avatar asked Dec 20 '22 01:12

MAPK


1 Answers

You can try this, using strsplit as mentioned by @Tensibai:

sp_vec <- strsplit(myvec, "/") # split the element of the vector by "/" : you will get a list where each element is the decomposition (vector) of one element of your vector, according to "/"
ts_vec <- lapply(sp_vec, # for each element of the previous list, do
                 function(x){
                     base <- sub("\\w$", "", x[1]) # get the common beginning of the column names (so first item of vector without the last letter)
                     x[-1] <- paste0(base, x[-1]) # paste this common beginning to the rest of the vector items (so the other letters)
                     x}) # return the vector
resvector <- unlist(ts_vec) # finally, unlist to get the needed vector

resvector
# [1] "IID:WE:G12D"   "IID:WE:G12V"   "IID:WE:G12A"   "GH:SQ:p.R172W" "GH:SQ:p.R172G" "HH:WG:p.S122F" "HH:WG:p.S122H"
like image 188
Cath Avatar answered Jan 13 '23 01:01

Cath