IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Foundations of Functional Programming with purrr

Visualizza il corso

Istruzioni dell'esercizio

  • 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.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

# 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
Modifica ed esegui il codice