Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorizing R loop for summation over vector section

I want to sum over certain sections of a vector. The length of these sections are given by another vector, let's say L = c(3,4). The vector whose elements should be summed up is vec = c(3,4,2,6,5,8,1) with length(vec) = sum(L). As result I want to have a vector sigma which 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 is just a small example and normally, L and vec have many more elements.

I want a fast solution for my problem. Probably reached through vectorization of my following 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]
}
like image 497
Stromberg Avatar asked Apr 25 '26 18:04

Stromberg


1 Answers

This should also work

diff(c(0,cumsum(vec)[cumsum(L)]))
like image 158
cryo111 Avatar answered Apr 28 '26 07:04

cryo111