[R] dist like function but where you can configure the method

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Fri May 16 18:12:09 CEST 2014


On Fri, May 16, 2014 at 4:46 PM, Witold E Wolski <wewolski at 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



More information about the R-help mailing list