模拟一系列代码 n(比如说 1000)次,同时将结果保存在 R 中的向量中

Simulate a series of code n(lets say 1000) times while saving the result in a vector in 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)