我想使用purrr模拟一些公平和不公平硬币的硬币翻转。我将rbinom
的参数作为数据框中的列。以下是我开始使用的一些代码:
library(tidyverse)
#setting up params for rbinom
params = list(size = 600, n = 1, p_fair = 0.5,p_unfair = 0.6)
params %>%
purrr::map_df(~rep(., times = 10))
如何使用purrr
将不同的参数p_fair
/ p_unfair
传递到rbinom
并将结果作为列放在我的数据框中?我希望结果看起来像:
size n p_fair p_unfair fair unfair
<dbl> <dbl> <dbl> <dbl> <int> <int>
1 600 1 0.5 0.6 308 373
2 600 1 0.5 0.6 305 367
3 600 1 0.5 0.6 280 367
4 600 1 0.5 0.6 299 374
5 600 1 0.5 0.6 298 360
6 600 1 0.5 0.6 298 346
7 600 1 0.5 0.6 301 359
8 600 1 0.5 0.6 292 376
9 600 1 0.5 0.6 300 347
10 600 1 0.5 0.6 305 357
答案 0 :(得分:1)
我们可以遍历'p_'列并应用rbinom
library(dplyr)
library(purrr)
df1 %>%
select(matches('p_')) %>%
map(~ df1 %>%
select(n, size) %>%
mutate(p = .x) %>%
pmap_int(rbinom)) %>%
bind_cols %>%
rename_all(funs(sub("p_", "", .))) %>%
bind_cols(df1, .)
另一种选择是使用gather
转换为'long'格式,应用rbinom
然后将其重新整形为'wide'
library(tidyr)
df1 %>%
gather(key, p, p_fair:p_unfair) %>%
mutate(rval = pmap_int(.[c('n', 'size', 'p')], rbinom)) %>%
separate(key, into = c('key1', 'key2')) %>%
select(-key1) %>%
group_by(key2) %>%
mutate(n1 = row_number()) %>%
select(-p) %>%
spread(key2, rval) %>%
select(-n1, -n, -size) %>%
bind_cols(df1, .)
df1 <- params %>%
map_df(~rep(., times = 10))
答案 1 :(得分:0)
直接的方法不如其他答案那么优雅,但更具可读性(并且不更长)。
# Libraries
library(tidyverse)
# Data
params = list(size = 600, n = 1, p_fair = 0.5,p_unfair = 0.6)
df1 <- params %>% map_df(~rep(., times = 10))
这里是对函数及其参数的提醒
# rbinom(n, size, prob)
创建包含所有参数的公平/不公平数据框(为相关参数命名的每个列标题)。
p_fair_vars <- df1 %>%
select(n, size, p = p_fair)
p_unfair_vars <- df1 %>%
select(n, size, p = p_unfair)
使用pmap
应用数据框。
df1 %>%
mutate(fair = pmap_int(p_fair_vars, rbinom),
unfair = pmap_int(p_unfair_vars, rbinom) )
#> # A tibble: 10 x 6
#> size n p_fair p_unfair fair unfair
#> <dbl> <dbl> <dbl> <dbl> <int> <int>
#> 1 600 1 0.5 0.6 296 351
#> 2 600 1 0.5 0.6 311 351
#> 3 600 1 0.5 0.6 290 356
#> 4 600 1 0.5 0.6 294 359
#> 5 600 1 0.5 0.6 294 348
#> 6 600 1 0.5 0.6 306 365
#> 7 600 1 0.5 0.6 288 370
#> 8 600 1 0.5 0.6 305 366
#> 9 600 1 0.5 0.6 314 327
#> 10 600 1 0.5 0.6 303 356
...或者:
df1 %>%
mutate(fair_vars = str_c(size, n, p_fair, sep="," ),
unfair_vars = str_c(size, n, p_unfair, sep = ","),
fair = pmap_int(p_fair_vars, rbinom),
unfair = pmap_int(p_unfair_vars, rbinom)) %>%
select(-c(5:6) )
由reprex package(v0.2.1)于2018-11-03创建