Home » How to Use the map() Function in R (With Examples)

How to Use the map() Function in R (With Examples)

by Erma Khan

The map() function from the purrr package in R can be used to apply some function to each element in a vector or list and return a list as a result.

This function uses the following basic syntax:

map(.x, .f)

where:

  • .x: A vector or list
  • .f: A function

The following examples show how to use this function in different scenarios.

Example 1: Use map() to Generate Random Variables

The following code shows how to use the map() function to generate three random variables that each contain five values that follow a standard normal distribution:

library(purrr)

#define vector
data #apply rnorm() function to each value in vector
data %>%
  map(function(x) rnorm(5, x))

[[1]]
[1] 0.0556774 1.8053082 2.6489861 2.2640136 1.1062672

[[2]]
[1] 1.450175 1.123048 3.413677 3.055304 2.713801

[[3]]
[1] 2.936732 2.157129 3.693738 2.994391 2.567040

For each element in the original vector, the map() function applied the rnorm() function to generate five random values that come from a standard normal distribution.

Example 2: Use map() to Transform Each Value in a Vector

The following code shows how to use the map() function to calculate the square of each value in a vector:

library(purrr)

#define vector
data #calculate square of each value in the vector
data %>%
  map(function(x) x^2)

[[1]]
[1] 4

[[2]]
[1] 16

[[3]]
[1] 100

[[4]]
[1] 225

[[5]]
[1] 400

For each element in the original vector, the map() function applied a function that calculated the square of each value.

Example 3: Use map() to Calculate Mean of Each Vector in List

The following code shows how to use the map() function to calculate the mean value of each vector in a list:

library(purrr)

#define list of vectors
data #calculate mean value of each vector in list
data %>%
  map(mean, na.rm=TRUE)

[[1]]
[1] 2

[[2]]
[1] 5

[[3]]
[1] 7.5

For each vector in the list, the map() function calculated the mean value.

From the output we can see:

  • The mean value of the first vector in the list is 2.
  • The mean value of the second vector in the list is 5.
  • The mean value of the third vector in the list is 7.5.

Note: The argument na.rm=TRUE tells R to ignore NA values when calculating the mean.

Additional Resources

The following tutorials explain how to use other common functions in R:

How to Use the tapply() Function in R
How to Use the dim() Function in R
How to Use the table() Function in R
How to Use sign() Function in R

Related Posts