Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 want 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 would be to use a for loop. I prefer doing it using apply/lapply/sapply/..., but the only way I can think of for doing 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 was a better way to do this. Is there?
(This may have been a bad example, but in general, is there a way to access elements of the list being iterated over, given that you know the position of these element relative to the current one?)

like image 417
user1482678 Avatar asked Dec 26 '22 12:12

user1482678


1 Answers

You may giggle, but there's 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
like image 84
Brandon Bertelsen Avatar answered Jan 31 '23 07:01

Brandon Bertelsen