Marc Schwartz
2011-Jun-07 21:07 UTC
[R] Generic function to split a vector by user defined values
Hi all, In follow up to my reply regarding splitting/grouping a vector: https://stat.ethz.ch/pipermail/r-help/2011-June/280361.html it seems logical that a generic approach might be useful. So here is one possibility, which I present for use and improvement as may be appropriate. x : a vector split: the value to use for the splits splitVec <- function(x, split) { is.na(x) <- x == split R1 <- rle(!is.na(x)) split(x, rep(cumsum(R1$values) * R1$values, R1$lengths))[-1] } So with Dave's original integer vector: x <- c(4, 5, 3, 0, 0, 0, 2, 4, 6, 4, 0, 0, 0, 2, 2, 0, 3, 4, 1, 0)> splitVec(x, 0)$`1` [1] 4 5 3 $`2` [1] 2 4 6 4 $`3` [1] 2 2 $`4` [1] 3 4 1 With a character vector: set.seed(1) Vec <- sample(c(letters[1:4], "Z"), 10, replace = TRUE)> Vec[1] "b" "b" "c" "Z" "b" "Z" "Z" "d" "d" "a"> splitVec(Vec, "Z")$`1` [1] "b" "b" "c" $`2` [1] "b" $`3` [1] "d" "d" "a" Hope that this might be useful to folks. Regards, Marc Schwartz