mapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE) Vectorize(FUN, vectorize.args = arg.names, SIMPLIFY = TRUE, USE.NAMES = TRUE)
FUN | the function to apply. |
... | the multiple list or vector arguments whose individual elements are passed to FUN. |
MoreArgs | an optional list of additional arguments passed to FUN. |
SIMPLIFY | a logical flag. If TRUE (the default), the result is simplified to a vector or a matrix, if possible. |
USE.NAMES | a logical flag. If TRUE (the default), the names of the first ... argument are used as the names for the result. |
vectorize.args | the arguments of FUN to be vectorized. The default is all argument names of FUN, other than any ... argument. |
mapply | returns a list, a vector, or a matrix. |
Vectorize | returns a function. See Details for more information. |
mapply(paste, 1:3, 4:6) # [1] "1 4" "2 5" "3 6"mapply(paste, 1:3, 4:8) # Warning message: # longer argument not a multiple of length of shorter # [1] "1 4" "2 5" "3 6" "1 7" "2 8"
mapply(paste, 1:3, 4:6, sep=LETTERS[1:3]) # [1] "1A4" "2B5" "3C6"
mapply(paste, 1:6, 7:9, MoreArgs=list(sep='-')) # [1] "1-7" "2-8" "3-9" "4-7" "5-8" "6-9"
mapply(paste, 1:2, 3:4, MoreArgs=list(sep='-'), SIMPLIFY=FALSE) # [[1]] # [1] "1-3" # # [[2]] # [1] "2-4"
# simplify to a matrix if FUN returns a vector, and SIMPLIFY=TRUE mapply(paste, 1:2, MoreArgs=list(3:4)) # [,1] [,2] # [1,] "1 3" "2 3" # [2,] "1 4" "2 4"
mapply(paste, 1:2, MoreArgs=list(3:4), SIMPLIFY=FALSE) # [[1]] # [1] "1 3" "1 4" # # [[2]] # [1] "2 3" "2 4"
# use names from first vectorized argument, if USE.NAMES=TRUE mapply(paste, c(aa=1,bb=2,cc=3), c(dd=4,ee=5,ff=6)) # aa bb cc # "1 4" "2 5" "3 6" mapply(paste, c(aa=1,bb=2,cc=3), c(dd=4,ee=5,ff=6), USE.NAMES=FALSE) # [1] "1 4" "2 5" "3 6"
# apply FUN to corresponding elements of a list and a vector mapply(matrix, list(aa = 1:12, bb=1:4, cc=1:6), nrow=c(3,2,2)) # $aa # [,1] [,2] [,3] [,4] # [1,] 1 4 7 10 # [2,] 2 5 8 11 # [3,] 3 6 9 12 # # $bb # [,1] [,2] # [1,] 1 3 # [2,] 2 4 # # $cc # [,1] [,2] [,3] # [1,] 1 3 5 # [2,] 2 4 6
rr <- function(x=42, times=1) rep.int(x,times=times) vrr <- Vectorize(rr) vrr(times=1:4) # [[1]] # [1] 42 # # [[2]] # [1] 42 42 # # [[3]] # [1] 42 42 42 # # [[4]] # [1] 42 42 42 42
f <- function(x=1:3, y=4:6) c(x,y) vf <- Vectorize(f, SIMPLIFY = FALSE) f(1:3,4:6) # [1] 1 2 3 4 5 6 vf(1:3,4:6) # [[1]] # [1] 1 4 # # [[2]] # [1] 2 5 # # [[3]] # [1] 3 6
vf(1:3) # Only vectorizes x (given), not y (default) # [[1]] # [1] 1 4 5 6 # # [[2]] # [1] 2 4 5 6 # # [[3]] # [1] 3 4 5 6
# vf2 only vectorizes argument x, even if y is given vf2 <- Vectorize(f, "x", SIMPLIFY = FALSE) vf2(1:3,11:13) # [[1]] # [1] 1 11 12 13 # # [[2]] # [1] 2 11 12 13 # # [[3]] # [1] 3 11 12 13