R Language: mapply()

0

The mapply() function in R is a multivariate apply function that applies a function to multiple list or vector arguments in parallel. It is similar to the lapply() function, but it takes multiple arguments and applies the function to each combination of arguments.

The syntax for mapply() is as follows:

mapply(FUN, args1, args2, ..., MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE)

  • FUN is the function to apply.
  • args1, args2, ... are the arguments to pass to FUN.
  • MoreArgs is a list of additional arguments to pass to FUN.
  • SIMPLIFY indicates whether the result should be simplified.
  • USE.NAMES indicates whether the names of the arguments should be used.

For example, the following code uses mapply() to calculate the product of all pairs of numbers in the vectors x and y:

x <- c(1, 2, 3, 4)

y <- c(5, 6, 7, 8)


mapply(function(x, y) x * y, x, y)

This code will output the following vector:

[1] 5 12 21 32

The mapply() function can be used to apply a function to multiple arguments in a variety of ways. It is a powerful tool that can be used to simplify and speed up your R code.

Examples of how to use the mapply() function

  • To calculate the mean of each column in a matrix, you could use the following code:

mapply(mean, matrix)

  • To calculate the standard deviation of each row in a data frame, you could use the following code:

mapply(sd, data.frame)

  • To create a list of vectors, each of which contains the elements of a vector that are greater than a certain value, you could use the following code:

mapply(function(x, threshold) x[x > threshold], vector, threshold)

Post a Comment

0Comments
Post a Comment (0)