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

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 <- 1:3

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

[]
 0.0556774 1.8053082 2.6489861 2.2640136 1.1062672

[]
 1.450175 1.123048 3.413677 3.055304 2.713801

[]
 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 <- c(2, 4, 10, 15, 20)

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

[]
 4

[]
 16

[]
 100

[]
 225

[]
 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 <- list(c(1, 2, 3),
c(4, 5, 6),
c(7, 8, NA))

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

[]
 2

[]
 5

[]
 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.