模拟一系列代码n次假设说1000次,同时将结果保存到R中的向量中

问题描述

我对R还是比较陌生,所以我一直在努力重复几次代码行,并为每次重复保存结果。

目标是在20年内随机(相等概率)分配多个事件,在我的情况下为100。由于天数无关紧要,因此我使用月数来定义时间段。随后,我将对20年内每24个月的事件进行一次计数。最后,提取24个月内发生的最大事件数。

尽管代码混乱而且效率低下,但它可以达到预期的目的。但是,我想重复此过程1000次,以获取24个月内发生的所有最大事件数的分布,以便与我的真实数据进行比较。

到目前为止,这是我的编码:

library(runner)
library(dplyr)

#First I set the period from the year 2000 to 2019 with one-month increments. 
period <- seq(as.Date("2000/1/1"),by = "month",length.out = 240)

#I sample random observations assigned to different months over the entire period. 
u <- sample(period,size=100,replace=T)

#Make a table in order to register the number of occurrences within each month. 
u <- table(u)

#Create a data frame to ease information processing. 
simulation <- data.frame(u)

#Change the date column to date format. 
simulation$u <- as.Date(simulation$u)

#Compute number of events taking place within every 24-month period (730 = days in 24 months). 
u <- u %>%
  mutate(
    Last_24_month_total = sum_run(
      x = simulation$Freq,k = 730,idx = as.Date(simulation$u,format = "%d/%m/%Y"))
  )

#extract the maximum number of uccurences within a 24 month period
max <- max(u$Last_24_month_total)

有人可以帮助我理解如何重写此过程,以便于进行一千次重复,同时保存每次重复的最大值。 谢谢

解决方法

如@jogo在评论中所建议,您可以使用replicate

我简化了您的代码。

library(runner)
library(dplyr)

seq_dates <- seq(as.Date("2000/1/1"),by = "month",length.out = 240)

replicate(100,seq_dates %>% 
           sample(100,replace = TRUE) %>% 
           table() %>% 
           sum_run(730,idx = as.Date(names(.))) %>% 
           max)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...