Using purrr::map with default/absent fn arguments

Well I can make a start at this one. Other more eloquent and knowledgable
community members can no doubt improve on this response!

To answer Question 1, you are only passing one value (3) to toy_func() to create toy_df2. You can
pass a vector c(3, 3) instead as in the example below. This works the same way as the toy_df3 code because the recycling happens during the creation of dummy_x. That is, dummy_x is a vector of length 2 which is then passed onto toy_func().

library(tidyverse)
toy_func <- function(k = 3) { rnorm(k) }
toy_df <- tibble(runs = 1:2)

set.seed(123)
toy_df %>% mutate(new_var = map(c(3, 3), toy_func)) %>% unnest()
#> # A tibble: 6 x 2
#>    runs new_var
#>   <int>   <dbl>
#> 1     1 -0.560 
#> 2     1 -0.230 
#> 3     1  1.56  
#> 4     2  0.0705
#> 5     2  0.129 
#> 6     2  1.72

In terms of Question 2 I'm not sure how to use map() when I only want to use the default function arguments. I'd use rerun() instead.

In summary, and in answer to Question 3, I'd use rerun() rather than map() as shown in the example below if only the default function arguments are required for toy_func().

set.seed(123)
toy_df %>% mutate(new_var = rerun(nrow(.), toy_func())) %>% unnest()
#> # A tibble: 6 x 2
#>    runs new_var
#>   <int>   <dbl>
#> 1     1 -0.560 
#> 2     1 -0.230 
#> 3     1  1.56  
#> 4     2  0.0705
#> 5     2  0.129 
#> 6     2  1.72

Created on 2018-08-17 by the reprex package (v0.2.0).

5 Likes