# [R] Speeding up

Van Campenhout Bjorn bjorn.vancampenhout at ua.ac.be
Mon Jul 9 15:12:13 CEST 2007

```Hi R-helpers,

I am new in programming and R, so this may be basic.  I need to speed up
a procedure where I minimize some function on different partitions of
the data. I can do this with a loop, as for instance in:

i<-1
meanmin<-Inf
while (i<length(x)) {
ind<-x<xord[i]
if (some function to be minimized<meanmin) {
meanmin<-some function to be minimized
indmin<-xord[i]
}
i<-i+1
}
print(indmin)

I learned that I should avoid loops, so I found the following
alternative:

dmat<-outer(x,xord,"<")*1
ss<-apply(dmat,2,function (z) some function to be minimized)
indmin<-xord[which.min(ss)]
print(indmin)

But this does not lead to spectacular improvements (obviously, this is
dependent on the function and the length of x, and this dmat does not
seem to be an elegant solution to me).  Is there scope for substantial
improvement? Any pointers will be greatly appreciated.  Below an example
with some timings.

> set.seed(12345)
> x <- rnorm(1000, mean = 5, sd = 2)
> xord<-x[order(x)]
>
> system.time({i<-1
+ meanmin<-Inf
+ while (i<length(x)) {
+ ind<-x<xord[i]
+ if ((mean(x*ind)+mean(x*!ind))<meanmin) {
+ meanmin<-mean(x*ind)+mean(x*!ind)
+ indmin<-xord[i]
+ }
+ i<-i+1
+ }
+ print(indmin)})
 3.826595
user  system elapsed
0.14    0.00    0.14
>
>
>
> system.time({dmat<-outer(x,xord,"<")*1
+ ss<-apply(dmat,2,function (z) mean(x*z)+mean(x*!z))
+ indmin<-xord[which.min(ss)]
+ print(indmin)})
 3.826595
user  system elapsed
0.42    0.06    0.49
>
>

```