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?)
source share