CommencerCommencer gratuitement

Simulating data 3+ inputs with pmap()

What if you need to iterate over three lists? Is there a map3()? To iterate over more than two lists, whether it's three, four, or even 20, you'll need to use pmap(). However, pmap() does require us to supply our list arguments a bit differently.

To use pmap(), you first need to create a master list of all the lists we want to iterate over. The master list is the input for pmap(). Instead of using .x or .y, use the list names as the argument names.

You are going to simulate data one more time, using five lists as inputs, instead of two. Using pmap() gives you complete control over our simulated dataset, and will allow you to use two different means and two different standard deviations along with the different sites.

Cet exercice fait partie du cours

Foundations of Functional Programming with purrr

Afficher le cours

Instructions

  • Create a named list containing the sites, means, means2, sigma, and sigma2 lists.
  • pmap() over the list of lists, to create a list of data frames with three columns; the first column is sites.
    • The second column is a, which is rnorm() with mean = means, and sd = sigma.
    • The third column is b, which is rnorm() with mean = means2, and sd = sigma2.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

# Create a master list, a list of lists
pmapinputs <- list(sites = ___,  means = ___, sigma = ___, 
                   means2 = ___, sigma2 = ___)

# Map over the master list
list_of_files_pmap <- pmap(___, 
  function(___, ___, ___, ___, ___) 
    data.frame(sites = ___,
        a = rnorm(mean = ___, n = 200, sd = ___),
        b = rnorm(mean = ___, n = 200, sd = ___)))
                           
list_of_files_pmap
Modifier et exécuter le code