map() in R

Functions
Published

March 19, 2023

In this blog, I’m going to explain the functionality of a R function, map().

Introduction

map() is a R function which is used to apply some function to each element in a vector or list and return a list as a result.

Function definition

map(.x, .f)

Definition of parameters

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

Examples

Example 1: Transform each value in a vector

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

library(purrr)

# To define vector
data <- c(2, 4, 10, 15, 20)

# To calculate log of each value in the vector
data %>%
  map(function(x) log10(x))
[[1]]
[1] 0.30103

[[2]]
[1] 0.60206

[[3]]
[1] 1

[[4]]
[1] 1.176091

[[5]]
[1] 1.30103
result <- data %>%
  map(function(x) log10(x))

To obtain the elements form the list:

result[[i]] ## i is the index of the list
result[[1]]
[1] 0.30103
result[[5]]
[1] 1.30103

Example 2: Generate random numbers for a list of sample size

# To define vector
sample_size <- c(3, 5, 8, 10)

# To calculate log of each value in the vector
sample_size %>%
  map(function(x) runif(x))
[[1]]
[1] 0.83657822 0.52427993 0.06325641

[[2]]
[1] 0.7281998 0.8435732 0.7056618 0.3041016 0.2060783

[[3]]
[1] 0.4010470 0.8529365 0.8437544 0.1792954 0.6787083 0.6724727 0.3594332
[8] 0.8774093

[[4]]
 [1] 0.807383182 0.508806102 0.549565474 0.917473407 0.189435094 0.278735327
 [7] 0.001623599 0.565823819 0.778334239 0.790809778
result_random <- sample_size %>%
  map(function(x) runif(x))

To obtain the elements form the list:

result_random[[1]] ## To obtain first list
[1] 0.07161259 0.81010021 0.53039259
result_random[[1]][2] ## To obtain second element of the first list
[1] 0.8101002