If there is a vector x with
length(x)
# 100
And there is a vector a, which denotes the leading index of subvector of x:
a
# 1, 5, 23, 79
Then I want to split x according to a as follow:
list(x[1:4], x[5:22], x[23:78], x[79:100])
Is there a quick way to do this in R?
Both the previous answers rely on making lists/vectors for splitting that are the same length as the original x vector. This might be inefficient in the instance of a very long vector and can be avoided:
Map(function(i,j) x[i:j], a, cumsum(diff(c(a, length(x)+1))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With