1
votes

I want to use tibble, df, a list of scenarios, myscenarios, and a simulation function ,simu, to create a result tibble with:

  1. 25 rows of data (five rows for each scenario)
  2. The result data frame should include the following columns: x, n, v, scenario, result

I would like to achieve this using the appropriate purrr function.

The reprex below provides the tibble, a list of five scenarios and the simu function. The current output simply utilizes the simu function against the df tibble.

Would lmap be the correct purrr function to achieve this? If so, would I have to use lmap in conjuction with mutate?

library(tidyverse)
df <- tibble(x= 1:5, 
             n= c("Jim","John","Jane","Jay","Jack"),
             v= 11:15)

myscenarios <- list("one", "two", "three", "four", "five")

simu <- function(x, v){
  x * v + sample(1:10, 1)
} 

result <- df %>% 
  mutate(result = simu(x, v))

result
#> # A tibble: 5 x 4
#>       x n         v result
#>   <int> <chr> <int>  <int>
#> 1     1 Jim      11     21
#> 2     2 John     12     34
#> 3     3 Jane     13     49
#> 4     4 Jay      14     66
#> 5     5 Jack     15     85

Created on 2020-11-23 by the reprex package (v0.3.0)

1
In the post, I don't see the myscenarios used in the functionakrun

1 Answers

1
votes

We can loop over the list of names with map, use assign (:=) while evaluating (!!) to assign the output to the names

library(dplyr)
library(purrr)
map_dfc(myscenarios, ~ df %>% 
                   transmute(!! .x := simu(x, v))) %>%
      bind_cols(df, .)

-output

# A tibble: 5 x 8
#      x n         v   one   two three  four  five
#  <int> <chr> <int> <int> <int> <int> <int> <int>
#1     1 Jim      11    16    17    20    13    15
#2     2 John     12    29    30    33    26    28
#3     3 Jane     13    44    45    48    41    43
#4     4 Jay      14    61    62    65    58    60
#5     5 Jack     15    80    81    84    77    79

If there are list of functions that correspond to the elements of 'myscenarios', we can loop over both with map2 and then apply the function (assuming they have the same arguments), on the dataset, return a single column with transmute and bind with the original dataset

lstfn <- list(simu, simu, simu, simu, simu)
map2_dfc(myscenarios, lstfn, ~ df %>%
         transmute(!! .x := .y(x, v))) %>%
     bind_cols(df, .)