我的问题是,我想重复一次随机抽样,直到达到一个标准,因为我目前已经实现了这意味着我将不得不添加行到我的数据帧。
以下是我目前拥有的代码:
library(tidyverse)
set.seed(1)
simulation_df = crossing(sim_mean = 1,
sim_sd = 2,
final_sample_size =20,
sim =1:10,
collected_data = c(6,14)) %>%
mutate(phase = if_else(collected_data == 6,
"pilot",
"full sample"),
data =pmap(list(collected_data, # input to rnorm
sim_mean,
sim_sd),
rnorm)) %>% # function to apply
group_by(sim) %>%
# check if pilot was successful (ie 4 or more data points > 0)
mutate( pilot_result = if_else(phase =="pilot",
map_dbl(data, ~ sum(. > 0)),
0 ),
success_pilot = pilot_result >= 4) %>%
ungroup()
(simulation_df %>% select(sim,phase, data, success_pilot) %>% head())
#> # A tibble: 6 x 4
#> sim phase data success_pilot
#> <int> <chr> <list> <lgl>
#> 1 1 pilot <dbl [6]> FALSE
#> 2 1 full sample <dbl [14]> FALSE
#> 3 2 pilot <dbl [6]> TRUE
#> 4 2 full sample <dbl [14]> FALSE
#> 5 3 pilot <dbl [6]> TRUE
#> 6 3 full sample <dbl [14]> FALSE
于2019-03-12由
reprex package
(第5.2.1节)
如果
success_pilot == FALSE
,我想重复采样6个数据点,直到
success_pilot == TRUE
. 我可以通过绕过一个最大的时间来实现这一点,我决定在6个数据点之后采样一次,然后在第一次之后过滤掉所有的数据点。
success_pilot==真
.
在迭代章节中
R for Data Science
,虽然提到了循环,但没有涉及-我想知道是否有一个整洁的解决方案?