Simulating data with multiple inputs using map2()
The map() function is great if you need to iterate over one list, however, you will often need to iterate over two lists at the same time. This is where map2() comes in. While map() takes the list as the .x argument; map2() takes two lists as two arguments: .x and .y.
To test out map2(), you are going to create a simple dataset, with one list of numbers and one list of strings. You will put these two lists together and create some simulated data.
This exercise is part of the course
Foundations of Functional Programming with purrr
Exercise instructions
- Create a
meanslist containing the values 1 through 3, each as a separate element. - Create a
siteslist with "north", "west", and "east". map2()over thesitesandmeanslists to create a data frame with two columns.- First column is
sites; second column is generated byrnorm()withmeanfrom themeanslist.
- First column is
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# List of 1, 2 and 3
means <- list(___)
# Create sites list
sites <- list(___)
# Map over two arguments: sites and means
list_of_files_map2 <- map2(___, ___, ~___(sites = ___,
a = rnorm(mean = ___, n = 200, sd = (5/2))))
list_of_files_map2