Wanted to see if someone has a more elegant solution. But what is the appropriate way to keep track of the current index while using apply. For example, suppose I wanted to take the sum ONLY from the current element I am evaluating going forward to the end of my vector.
Is this the best way to do it?
y = rep(1,100)
apply(as.matrix(seq(1:length(y))),1,function(x) { sum(y[x:length(y)])})
I appreciate your input.
This looks more like a task for sapply
:
sapply(seq_along(y), function(x){sum(y[x:length(y)])})
For your specific example, there are loads of other options (like reversing the vector y
and then using cumsum
), but I guess this is the general pattern:
use seq_along
or at worst seq
to get the sequence you are interested in, and pass this to *apply
.
rev(cumsum(y))
would be a lot faster in the current instance:
> y = rep(1,100000)
> system.time(apply(as.matrix(seq(1:length(y))),1,function(x) { sum(y[x:length(y)])}) )
user system elapsed
88.108 88.639 176.094
> system.time( rev(cumsum(y)) )
user system elapsed
0.002 0.001 0.004
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With