Brian Pellerin
Brian Pellerin

Reputation: 111

Splitting a vector

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?

Upvotes: 4

Views: 600

Answers (3)

Richie Cotton
Richie Cotton

Reputation: 121177

Collapse into one string, then split on the "Y"s.

x <- c("Y", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "Y", "N", "N", "N", "N")
y <- paste(x, collapse = "")
z <- paste("Y", strsplit(pn, "Y")[[1]], sep = "")[-1]
z

Or using run length encoding.

n <- rle(x)$lengths[c(FALSE, TRUE)]
lapply(n, function(i) paste("Y", rep.int("N", i), sep = "", collapse = ""))

(This give you a list rather than a vector. Use unlist if this isn't what you want.)

Upvotes: 3

Joshua Ulrich
Joshua Ulrich

Reputation: 176728

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=""))

Upvotes: 7

Nick Sabbe
Nick Sabbe

Reputation: 11956

There are surely better ways, but:

tst<-c("Y", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "Y", "N", "N", "N", "N")
starts<-which(tst=="Y") #where are the "Y"
ends<-c(starts[-1]-1, length(tst)) #pos before each "Y""
lapply(seq_along(starts), function(i){tst[(starts[i]):(ends[i])]}) #parts from each start till each end

Upvotes: 3

Related Questions