Avoid two for loops in R

前端 未结 6 762
执念已碎
执念已碎 2021-02-08 11:15

I have a R code that can do convolution of two functions...

convolveSlow <- function(x, y) {  
nx <- length(x); ny <- length(y)  
xy <- numeric(nx          


        
6条回答
  •  南笙
    南笙 (楼主)
    2021-02-08 11:49

    As Dirk says, compiled code can be a lot faster. I had to do this for one of my projects and was surprised at the speedup: ~40x faster than Andrie's solution.

    > a <- runif(10000)
    > b <- runif(10000)
    > system.time(convolveFast(a, b))
       user  system elapsed 
      7.814   0.001   7.818 
    > system.time(convolveC(a, b))
       user  system elapsed 
      0.188   0.000   0.188 
    

    I made several attempts to speed this up in R before I decided that using C code couldn't be that bad (note: it really wasn't). All of mine were slower than Andrie's, and were variants on adding up the cross-product appropriately. A rudimentary version can be done in just three lines.

    convolveNotAsSlow <- function(x, y) {
      xyt <- x %*% t(y)
      ds <- row(xyt)+col(xyt)-1
      tapply(xyt, ds, sum)
    }
    

    This version only helps a little.

    > a <- runif(1000)
    > b <- runif(1000)
    > system.time(convolveSlow(a, b))
       user  system elapsed 
      6.167   0.000   6.170 
    > system.time(convolveNotAsSlow(a, b))
       user  system elapsed 
      5.800   0.018   5.820 
    

    My best version was this:

    convolveFaster <- function(x,y) {
      foo <- if (length(x)=0 & bar.rc

    This was quite a bit better, but still not nearly as fast as Andrie's

    > system.time(convolveFaster(a, b))
       user  system elapsed 
      0.280   0.038   0.319 
    

提交回复
热议问题