Vectorization of cycle R for summation over vector cut

I want to sum certain parts of a vector. The length of these sections is given by another vector, say L = c(3,4)

. The vector whose elements are to be summed, vec = c(3,4,2,6,5,8,1)

c length(vec) = sum(L)

. As a result, I want to have a vector sigma

that contains the sum over sum(vec[1:L[1]])

and, sum(vec[(L[1]+1):L[2]])

or in this example, sum(vec[1:3])

and sum(vec[4:7])

. In this small example, the solution would be: sigma[1] = 3+4+2 = 9

and sigma[2] = 6+5+8+1 = 20

. Please note that this is just a small sample, and normally L

and vec

have a lot more items.

I want a quick solution to my problem. Probably achieved by vectorizing my next loop:

L = c(3,4)       #length of sections
vec = c(3,4,2,6,5,8,1)  #creating vector for summation
L_cum = c(0,cumsum(L))  #creating vector for the length of sections with needed indices
sigma = 0
for(i in 1:length(L)){
 sigma[i] = sum(vec[(L_cum[i]+1):L_cum[i+1]])  #summation over vec[1:3] and vec[4:7]
}

      

+3


source to share


2 answers


This should work as well



diff(c(0,cumsum(vec)[cumsum(L)]))

      

+5


source


you must use



x <- rep(seq_along(L), L) # from akrun comment
tapply(vec, x, sum)
 1  2 
 9 20 

      

+3


source







All Articles