The mapply()
function in R is used to apply a function FUN
to a given list or a vector argument passed to it.
mapply(FUN, …, MoreArgs = NULL, SIMPLIFY = TRUE,USE.NAMES = TRUE)
The mapply()
function takes the following parameter values:
FUN
: This is the function to apply to the provided vector arguments. It is a required parameter.
...
: This is a list of the arguments to which the FUN
is applied. It is a required parameter.
MoreArgs
: This is a list of other vector arguments to FUN
. It is an optional parameter.
SIMPLIFY
: This takes a logical value (TRUE
or FALSE
) indicating whether the result is reduced to a vector, matrix, or an array of higher dimensions. It is an optional parameter.
USE.NAMES
: This takes a logical value indicating whether to use the name if the first argument of the function has names, or use a character vector if the argument is a character vector. It is an optional parameter.
The mapply()
function returns a list or if the argument, SIMPLICITY
= TRUE
, a vector, array, or list.
Let's look at the code below:
# creating a functionmyfunction <- function(a, b, c) {a*b + c}# creating a list of vector argumentsa = c(1, 4, 0, 6)b = c(1, 2, 3, 0)c = c(5, 0, 4, 3)# applying the function over the list of argumentsmapply(myfunction, a, b, c)
Line 2: We create a function, myfunction
, using the function()
function.
Lines 7 to 9: We create a list of vector arguments, a
, b
, and c
.
Line 12: We implement the mapply()
function on the function myfunction
and the list of vector arguments provided. The result is printed to the console.