Is there a way to vectorize operations that access multiple elements of a vector?

Let's say I have a vector of integers:

> a<-sample(1:100,10) > a [1] 13 23 97 70 63 32 82 31 15 36 

And I need a vector containing the cumulative values โ€‹โ€‹of this vector. That is, I want the vector 13 36 133 203 266 298 380 411 426 462

One way to achieve this is to use a for loop. I prefer to do this with apply / lapply / sapply / ..., but the only way I can come up with this is:

 sapply(1:length(a), function(x) {sum(a[1:x])}) [1] 13 36 133 203 266 298 380 411 426 462 

This works, but I was wondering if there is a better way to do this. Whether there is a? (This may have been a bad example, but is there generally a way to access the elements of the renamed list, given that you know the position of this element relative to the current?)

+4
source share
1 answer

You can giggle, but there is already a built-in function for this, see cumsum

 x <- sample(1:100,20) x [1] 32 42 54 79 92 69 96 41 51 22 74 76 86 37 85 99 3 11 17 57 cumsum(x) [1] 32 74 128 207 299 368 464 505 556 578 652 728 814 851 936 [16] 1035 1038 1049 1066 1123 
+10
source

All Articles