I'm trying to see if there is a better way to split vector into list in such a way that all consecutive unique values are put in one group.
Note that the method has to work when x
is character too.
#DATA
x = c(0, 0, 0, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7)
x
#[1] 0 0 0 7 7 7 7 0 0 0 0 0 0 0 7 7 7 7
#DESIRED OUTPUT
L = list(c(0, 0, 0), c(7, 7, 7, 7), c(0, 0, 0, 0, 0, 0, 0), c(7, 7, 7, 7))
L
#[[1]]
#[1] 0 0 0
#[[2]]
#[1] 7 7 7 7
#[[3]]
#[1] 0 0 0 0 0 0 0
#[[4]]
#[1] 7 7 7 7
#CURRENT APPROACH
split_vector = 0
for (i in 2:length(x)){
split_vector[i] = ifelse(x[i] != x[i-1], max(split_vector) + 1, split_vector[i-1])
}
split(x, split_vector)
#$`0`
#[1] 0 0 0
#$`1`
#[1] 7 7 7 7
#$`2`
#[1] 0 0 0 0 0 0 0
#$`3`
#[1] 7 7 7 7