简体   繁体   English

我将如何使用 purrr 根据场景列表和模拟功能多次运行模拟

[英]How would I use purrr to run a simulation multiple time based upon a list of scenarios and a simulation function

I want to use tibble, df , a list of scenarios, myscenarios , and a simulation function , simu , to create a result tibble with:我想用tibble,DF,情景模式,myscenarios列表,以及一个模拟功能,SIMU,来创建一个结果tibble:

  1. 25 rows of data (five rows for each scenario) 25 行数据(每个场景 5 行)
  2. The result data frame should include the following columns: x, n, v, scenario, result结果数据框应包括以下列:x、n、v、场景、结果

I would like to achieve this using the appropriate purrr function.我想使用适当的 purrr 函数来实现这一点。

The reprex below provides the tibble, a list of five scenarios and the simu function.下面的 reprex 提供了 tibble、五个场景的列表和 simu 函数。 The current output simply utilizes the simu function against the df tibble.当前输出仅使用针对 df tibble 的 simu 函数。

Would lmap be the correct purrr function to achieve this? lmap 是实现此目的的正确 purrr 函数吗? If so, would I have to use lmap in conjuction with mutate?如果是这样,我是否必须将 lmap 与 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)reprex 包(v0.3.0) 于 2020 年 11 月 23 日创建

We can loop over the list of names with map , use assign ( := ) while evaluating ( !! ) to assign the output to the names我们可以使用map遍历名称list ,在评估 ( !! ) 时使用 assign ( := ) 将输出分配给名称

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如果有对应于“myscenarios”元素的函数list ,我们可以用map2循环,然后应用该函数(假设它们具有相同的参数),在数据集上,使用transmute返回单个列并绑定原始数据集

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM