Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split a vector into a list of vectors when a condition is met?

Tags:

split

r

I would like to split a vector of into a list of vectors. The resulting vectors will be of variable length, and I need the split to occur only when certain conditions are met.

Sample data:

set.seed(3)
x <- sample(0:9,100,repl=TRUE)

For example, in this case I would like to split the above vector x at each 0.

Currently I do this with my own function:

ConditionalSplit <- function(myvec, splitfun) {
  newlist <- list()
  splits <- which(splitfun(x))
  if (splits == integer(0)) return(list(myvec))
  if (splits[1] != 1) newlist[[1]] <- myvec[1:(splits[1]-1)]
  i <- 1
  imax <- length(splits)

  while (i < imax) {
    curstart <- splits[i]
    curend <- splits[i+1]
    if (curstart != curend - 1)
      newlist <- c(newlist, list(myvec[curstart:(curend-1)]))
    i <- i + 1
  }

  newlist <- c(newlist, list(myvec[splits[i]:length(vector)]))
  return(newlist)
}

This function gives the output I'd like, but I'm certain there's a better way than mine.

> MySplit <- function(x) x == 0

> ConditionalSplit(x, MySplit)

[[1]]
 [1] 1 8 3 3 6 6 1 2 5 6 5 5 5 5 8 8 1 7 8 2 2

[[2]]
[1] 0 1

[[3]]
 [1] 0 2 7 5 9 5 7 3 3 1 4 2 3 8 2 5 2 2 7 1 5 4 2
...
like image 921
Will Beason Avatar asked Jan 30 '26 08:01

Will Beason


1 Answers

The following line seems to work just fine:

split(x,cumsum(x==0))
like image 183
Vincent Guillemot Avatar answered Feb 01 '26 22:02

Vincent Guillemot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!