Hello,

The compiler package is good at speeding up for loops but in this case the gain is neglectable. The ks test is the real time problem.

library(compiler)

f1 <- function(n){
        for(i in 1:100){
                for(i in 1:100){
                        ks.test(runif(100),runif(100))
                }
        }
}

f1.c <- cmpfun(f1)

system.time(f1())
   user  system elapsed
   3.50    0.00    3.53
system.time(f1.c())
   user  system elapsed
   3.47    0.00    3.48


Rui Barradas

Em 16-05-2014 17:12, Barry Rowlingson escreveu:
On Fri, May 16, 2014 at 4:46 PM, Witold E Wolski <wewol...@gmail.com> wrote:
Dear Jari,

Thanks for your reply...

The overhead would be
2 for loops
for(i in 1:dim(x)[2])
for(j in i:dim(x)[2])

isn't it? Or are you seeing a different way to implement it?

A for loop is pretty expensive in R. Therefore I am looking for an
implementation similar to apply or lapply were the iteration is made
in native code.

No, a for loop is not pretty expensive in R -- at least not compared
to doing a k-s test:

  > system.time(for(i in 1:10000){ks.test(runif(100),runif(100))})
    user  system elapsed
   3.680   0.012   3.697

  3.68 seconds to do 10000 ks tests (and generate 200 runifs)

  > system.time(for(i in 1:10000){})
    user  system elapsed
   0.000   0.000   0.001

  0.000s time to do 10000 loops. Oh lets nest it for fun:

  > system.time(for(i in 1:100){for(i in 
1:100){ks.test(runif(100),runif(100))}})
    user  system elapsed
   3.692   0.004   3.701

  no different. Even a ks-test with only 5 items is taking me 2.2 seconds.

Moral: don't worry about the for loops.

Barry

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to