【发布时间】:2020-12-21 15:45:08
【问题描述】:
我对 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)
有人可以帮助我了解如何重写此过程以促进一千次重复,同时保存每次重复的最大值吗? 谢谢
【问题讨论】:
-
最终你可以使用
replicate()
标签: r simulation