Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split vector by location

Tags:

r

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?

like image 451
wush978 Avatar asked Dec 14 '22 21:12

wush978


1 Answers

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))))
like image 163
thelatemail Avatar answered Feb 04 '23 10:02

thelatemail