Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a vector

Tags:

r

I have a vector x made up of "Y" and "N".

> x
 [1] Y N N N N N N N N N N Y N N N N

I would like to split this into

> x1
 [1] Y N N N N N N N N N N 

and

> x2
 [1] Y N N N N 

These vectors always start with a "Y" and take in all "N"s before the next "Y". Suggestions on how to do this?

like image 213
Brian Pellerin Avatar asked Dec 12 '22 12:12

Brian Pellerin


1 Answers

You can use a combination of cumsum and split to do this with a one-liner:

x <- c("Y","N","N","N","N","N","N","N","N","N","N","Y","N","N","N","N")
v <- split(x,paste("x",cumsum(x=="Y"),sep=""))
like image 192
Joshua Ulrich Avatar answered Jan 02 '23 09:01

Joshua Ulrich