【问题标题】:Simulate a series of code n(lets say 1000) times while saving the result in a vector in R模拟一系列代码 n(比如说 1000)次,同时将结果保存在 R 中的向量中
【发布时间】: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


【解决方案1】:

正如@jogo 在 cmets 中建议的那样,您可以使用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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多