简体   繁体   English

如何在 R 中使用 MonteCarlo() 正确运行 Monte Carlo 模拟

[英]How to properly run Monte Carlo simulation using MonteCarlo() in R

I need to run a monte carlo simulation by iterating an experiment a number of times.我需要通过多次迭代实验来运行蒙特卡罗模拟。 The functionality of the MonteCarlo package seems to lend itself well to this problem. MonteCarlo 包的功能似乎很好地解决了这个问题。 The experiment involves creating 4 matrices (a, b, c, and d) one after another, for each iteration.该实验涉及为每次迭代一个接一个地创建 4 个矩阵(a、b、c 和 d)。

Matrix a:矩阵a:

random.sample <- sample(1:100, 1000, replace = TRUE) 
a = matrix(random.sample, nrow = 10, ncol = 10, byrow = TRUE)        

Matrix b:矩阵 b:

b <- apply(a[, 1:10], 2, SMA, n=3)

Matrix c:矩阵 c:

c <- pmax(a, b)

Probability sequence:概率序列:

probability.sequence <- seq(0.1, 0.90, 0.1)

Matrix d:矩阵 d:

d <- apply(c, 2, quantile, probs = probability.sequence, na.rm = TRUE)

I would like to iterate the creation of matrices a through d a given amount of times, n .我想迭代矩阵ad的创建次数, n Each iteration should produce a new matrix d containing percentile calculations from the corresponding matrix c .每次迭代都应生成一个新矩阵d ,其中包含来自相应矩阵c 的百分位计算。 I would like to aggregate the results of the iteration process such that I get a mean, variance, upper confidence limit, and lower confidence limit of the 90% percentile from all matrix d 's.我想汇总迭代过程的结果,以便从所有矩阵d中获得 90% 百分位数的均值、方差、置信上限和置信下限。

(Approximate) DESIRED OUTPUT: (近似值)期望输出:

str(monte.carlo.aggregate.results)
num [1, 1:4] 65 15 85 45 
monte.carlo.aggregate.results         
     mean variance Upper CL Lower CL
[1,]   65       15       85       45

I have read ?MonteCarlo and have struggled to wrap the creation of matrices a through d in a function to be used with the MonteCarlo() function included in the MonteCarlo package.我读过?MonteCarlo并且一直在努力将矩阵 a 到 d 的创建包装在一个函数中,以便与 MonteCarlo 包中包含的MonteCarlo()函数一起使用。 Does anyone have advice for setting up this process for use with MonteCarlo() , or perhaps an alternate solution involving a custom for loop?有没有人有关于设置此过程以与MonteCarlo()一起使用的建议,或者可能涉及自定义 for 循环的替代解决方案?

If you don't insist on using the MonteCarlo package (which is new to me and looks interesting) you could wrap your code into a function.如果您不坚持使用MonteCarlo包(这对我来说是新的并且看起来很有趣),您可以将代码包装到一个函数中。

First, creating a random matrix with only the desired 90%-row.首先,创建一个只有所需 90% 行的随机矩阵。 Then, after specifying the amount, you can do the iterations and pack them into a list with lapply() .然后,在指定数量后,您可以进行迭代并使用lapply()将它们打包到一个列表中。 At the end just create an other matrix with your (rounded) statistics.最后,只需使用您的(四舍五入)统计数据创建另一个矩阵。

Something like this:像这样的东西:

set.seed(54897)  # setting seed for sake of reproducibility
probability.sequence <- seq(0.1, 0.90, 0.1)

# iteration function
mx <- function(X, n) {
  random.sample <- sample(1:1e2, 1e3, replace = TRUE) 
  a = matrix(random.sample, nrow = 10, ncol = 10, byrow = TRUE)  
  b <- apply(a[ ,1:10], 2, SMA, n = 3)
  c <- pmax(a, b)
  d <- apply(c, 2, quantile, probs = probability.sequence,  na.rm = TRUE)
  return(d[9, ])  # returns only the desired 90 % row
}

# amount of iterations
amount <- 1e3 

# iteration
mx.lst <- lapply(1:amount, mx)

# matrix for statistics
r = matrix(NA, nrow = 1, ncol = 4, 
           dimnames = list(NULL, c("mean", "variance", "Upper CL", "Lower CL")))
r[, 1] <- (mean(unlist(lapply(mx.lst, mean))))  # mean
r[, 2]  <- sqrt(var(unlist(lapply(mx.lst, mean))))  # variance
r[, 3]  <- r[, 1] - 1.96 * sqrt(r[, 2])  # lower CI 95 %
r[, 4]  <- r[, 1] + 1.96 * sqrt(r[, 2])  # upper CI 95 %

# output
(monte.carlo.aggregate.results <- round(r, 0))
#      mean variance Upper CL Lower CL
# [1,]   82        3       78       86

str(monte.carlo.aggregate.results)
# num 1, 1:4] 82 3 78 86
# - attr(*, "dimnames")=List of 2
# ..$ : NULL
# ..$ : chr [1:4] "mean" "variance" "Upper CL" "Lower CL"

# speed test
amount <- 1e4
system.time(mx.lst <- lapply(1:amount, mx))
#     user      system     elapsed 
#    48.21        0.00       48.31 

Note: please check yourself if the used formula for the confidence interval fits to your needs.注意:请自行检查所使用的置信区间公式是否符合您的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM