어떻게 purrr을 사용하여 시나리오 목록과 시뮬레이션 기능을 기반으로 시뮬레이션을 여러 번 실행합니까?
tibble, df , 시나리오 목록, myscenarios 및 시뮬레이션 함수 simu 를 사용하여 다음을 사용하여 결과 tibble을 만들고 싶습니다.
- 25 행의 데이터 (각 시나리오 당 5 행)
- 결과 데이터 프레임에는 x, n, v, 시나리오, 결과 열이 포함되어야합니다.
적절한 purrr 기능을 사용하여 이것을 달성하고 싶습니다.
아래 reprex는 tibble, 5 가지 시나리오 목록 및 simu 함수를 제공합니다. 전류 출력은 단순히 df tibble에 대해 simu 함수를 사용합니다.
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)
답변
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, .)