Created
October 4, 2014 03:34
-
-
Save mrdwab/3c09f9419cd2b78eb19c to your computer and use it in GitHub Desktop.
`lapply`/`sapply`/`vapply`/`rapply` comparison for http://stackoverflow.com/questions/26183929/r-sum-the-elements-of-each-list-on-a-list-and-return-the-result-in-a-data-frame
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
set.seed(1) | |
matches <- replicate(1000000, sample(20, sample(20), TRUE)) | |
fun1 <- function() unlist(lapply(matches, sum)) | |
fun2 <- function() sapply(matches, sum) | |
fun3 <- function() vapply(matches, sum, numeric(1L)) | |
fun4 <- function() rapply(matches, sum) | |
library(microbenchmark) | |
microbenchmark(L = fun1(), S = fun2(), V = fun3(), R = fun4(), times = 10) | |
# Unit: seconds | |
# expr min lq mean median uq max neval | |
# L 2.380785 2.878558 3.133040 3.121355 3.546682 3.805213 10 | |
# S 3.850449 4.199360 4.701659 4.645064 5.207675 5.784831 10 | |
# V 2.200894 2.263745 2.481544 2.460322 2.511168 3.254304 10 | |
# R 1.826686 1.975989 2.507679 2.638597 2.843158 2.988120 10 |
josilber
commented
Oct 4, 2014
@josilber -- your system is faster than mine :-)
What OS? I wonder what else would contribute to such a difference....
Here's what I get for the same:
matches <- lapply(1:100000, function(x) rnorm(sample(1:20)))
library(microbenchmark)
microbenchmark(S = sapply(matches, sum),
V = vapply(matches, sum, numeric(1L)),
L = unlist(lapply(matches, sum)),
R = rapply(matches, sum), times = 20)
# Unit: milliseconds
# expr min lq mean median uq max neval
# S 325.6060 344.6757 393.8432 373.3158 431.6990 525.2846 20
# V 174.7915 202.6937 225.3824 211.1571 241.4224 336.0206 20
# L 206.3639 217.1771 257.6876 240.8964 269.2399 386.8028 20
# R 141.8952 166.1317 187.5034 183.7426 201.6174 285.7413 20
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment