Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping track of current index when using apply

Tags:

r

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.

like image 352
Dave Avatar asked Oct 12 '11 12:10

Dave


2 Answers

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.

like image 74
Nick Sabbe Avatar answered Sep 27 '22 22:09

Nick Sabbe


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 
like image 25
IRTFM Avatar answered Sep 27 '22 20:09

IRTFM