, lapply(), . :
x <- 1:10
unlist(lapply(2:4, function(y) x*y))
# OR
unlist(lapply(2:4, function(x=x,y) x*y))
-, , outer():
xf <- 1:10
yf <- 2:4
c(xf %o% yf)
c(outer(xf,yf,FUN = `*`))
mapply, MoreArgs, rep :
xf <- 1:10
yf <- 2:4
mapply(function(x,y) x*y,
y = yf,
MoreArgs = list(x = xf))
lapply(), . SIMPLIFY = FALSE unlist():
unlist(mapply(function(x,y) x*y,
y = yf,
MoreArgs = list(x = xf),
SIMPLIFY = FALSE))
, . , R, , outer() , .
, , ( ). , :
outer() , .mapply() , sapply() .
: :
fx <- sample(1e4)
fy <- sample(1e3)
library(microbenchmark)
microbenchmark(sapply = as.vector(sapply(fx, function(x, y) x * y, fy)),
mapply = mapply( FUN = function(x, y) x * y, fx, rep( fy, each = 1e4)),
sapply2 = as.vector(sapply(fx, function(y) sapply(fy, function(x) x * y))),
outer = c(outer(fx, fy, function(x, y) x * y)),
mapply2 = mapply(function(x,y) x*y, x=fx, MoreArgs = list(y = fy)),
mapply3 = mapply(function(x,y) x*y, y=fy, MoreArgs = list(x = fx)),
times = 15)
:
Unit: milliseconds
expr min lq mean median uq max neval cld
sapply 89.52318 92.98653 344.1538 117.11280 239.64887 1485.3178 15 a
mapply 20471.02137 22925.42757 24478.5985 24650.29055 25627.31232 28840.3494 15 c
sapply2 7472.02251 8268.04696 9519.8016 8707.19193 9528.46181 14182.7537 15 b
outer 77.62331 85.94651 189.5107 91.83722 182.08506 1119.6620 15 a
mapply2 77.76871 79.71924 143.9484 81.24168 84.53247 971.1792 15 a
mapply3 65.21709 71.85662 107.9586 73.80779 124.21141 242.0760 15 a