I want to apply a function with multiple variables with different values to a list. I know how to do this with one changing variable
sapply(c(1:10), function(x) x * 2)
# [1] 2 4 6 8 10 12 14 16 18 20
but not with two. I show you first manually what I want (actually I use lapply()
but sapply()
is more synoptic in SO):
# manual
a <- sapply(c(1:10), function(x, y=2) x * y)
b <- sapply(c(1:10), function(x, y=3) x * y)
c <- sapply(c(1:10), function(x, y=4) x * y)
c(a, b, c)
# [1] 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12
# [24] 16 20 24 28 32 36 40
And this is my attempt where I try to define both x
and y
.
# attempt
X <- list(x = 1:10, y = 2:4)
sapply(c(1:10, 2:4), function(x, y) x * y)
# Error in FUN(X[[i]], ...) : argument "y" is missing, with no default
Benchmark of solutions
library(microbenchmark)
microbenchmark(sapply = as.vector(sapply(1:10, function(x, y) x * y, 2:4)),
mapply = mapply( FUN = function(x, y) x * y, 1:10, rep( x = 2:4, each = 10)),
sapply2 = as.vector(sapply(1:10, function(y) sapply(2:4, function(x) x * y))),
outer = c(outer(1:10, 2:4, function(x, y) x * y)))
# Unit: microseconds
# expr min lq mean median uq max neval
# sapply 34.212 36.3500 62.44864 39.1295 41.9090 2304.542 100
# mapply 62.008 65.8570 87.82891 70.3470 76.5480 1283.342 100
# sapply2 196.714 203.9835 262.09990 223.6550 232.2080 3344.129 100
# outer 7.698 10.4775 13.02223 12.4020 13.4715 53.883 100
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…