What is the mapply() function in R?
Overview
The mapply() function in R is used to apply a function FUN to a given list or a vector argument passed to it.
Syntax
mapply(FUN, …, MoreArgs = NULL, SIMPLIFY = TRUE,USE.NAMES = TRUE)
Parameter value
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 theFUNis applied. It is a required parameter.MoreArgs: This is a list of other vector arguments toFUN. It is an optional parameter.SIMPLIFY: This takes a logical value (TRUEorFALSE) 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.
Return value
The mapply() function returns a list or if the argument, SIMPLICITY = TRUE, a vector, array, or list.
Code example
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)
Code explanation
Line 2: We create a function,
myfunction, using thefunction()function.Lines 7 to 9: We create a list of vector arguments,
a,b, andc.Line 12: We implement the
mapply()function on the functionmyfunctionand the list of vector arguments provided. The result is printed to the console.