Is R's apply family more than syntactic sugar?

后端 未结 5 2335
旧时难觅i
旧时难觅i 2020-11-21 22:14

...regarding execution time and / or memory.

If this is not true, prove it with a code snippet. Note that speedup by vectorization does not count. The speedup must c

5条回答
  •  你的背包
    2020-11-21 22:32

    ...and as I just wrote elsewhere, vapply is your friend! ...it's like sapply, but you also specify the return value type which makes it much faster.

    foo <- function(x) x+1
    y <- numeric(1e6)
    
    system.time({z <- numeric(1e6); for(i in y) z[i] <- foo(i)})
    #   user  system elapsed 
    #   3.54    0.00    3.53 
    system.time(z <- lapply(y, foo))
    #   user  system elapsed 
    #   2.89    0.00    2.91 
    system.time(z <- vapply(y, foo, numeric(1)))
    #   user  system elapsed 
    #   1.35    0.00    1.36 
    

    Jan. 1, 2020 update:

    system.time({z1 <- numeric(1e6); for(i in seq_along(y)) z1[i] <- foo(y[i])})
    #   user  system elapsed 
    #   0.52    0.00    0.53 
    system.time(z <- lapply(y, foo))
    #   user  system elapsed 
    #   0.72    0.00    0.72 
    system.time(z3 <- vapply(y, foo, numeric(1)))
    #   user  system elapsed 
    #    0.7     0.0     0.7 
    identical(z1, z3)
    # [1] TRUE
    

提交回复
热议问题