Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

r - How to define multiple variables with lapply?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use mapply()

mapply() applies a function to multiple list or vector arguments.

rep() was also used to repeat the values 2, 3, and 4. Specifying 10 in the each parameter, rep() repeats each element of x 10 times.

This is necessary since the first argument in mapply() - 1:10 - is of length 10.

# supply the function first, followed by the
# arguments in the order in which they are called in `FUN`
mapply( FUN = function(x, y) x * y
        , 1:10
        , rep( x = 2:4, each = 10)
)

# [1]   2  4  6  8 10 12 14 16 18 20  3  6  9 12 15 18 21 24 27 30  4  8 12 16 20
# [26] 24 28 32 36 40

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...