[R] Improving performance by rewriting for loops into apply functions

Aleš Grm grm.ales at gmail.com
Sat Jul 23 01:16:18 CEST 2016


Hello,

I have a slight performance issue that I'd like to solve by rewriting a
short bit of code that uses for loops so that it would use apply in order
to get some performance gains. My problem is that I can't modify the
variables that are passed to apply function during apply functions
execution and use it's latest results. My first thought was to use apply
functions but if this isn't possible I'm open to other suggestions.

For example:
path1 = matrix(c(1,2,3,4,5), ncol=1);
path2 = matrix(c(1,2,3,4,5,6), ncol=1);
apply(path1, 2, function(x, path2){
  tmp = x*path2[x+1];
  path2[x+1] = tmp;
  return(tmp);
}, path2)

In the code above, path2 should have its elements updated in the course of
the apply function and its value should be use in the next iteration while
executing apply function but that doesn't happen. It seems that when a
variable is passed into apply function (path2) it is immutable.

BR Aleš

	[[alternative HTML version deleted]]



More information about the R-help mailing list