【问题标题】:simulations In R with apply and replicate在 R 中使用应用和复制进行模拟
【发布时间】:2017-08-29 14:31:58
【问题描述】:

我有两个矩阵一个包含所有平均值,另一个包含所有标准差。我想为三个投资者中的每一个模拟一个随机数,看看哪个投资者得到的最高。 例如:- 贷款 1 有三个投资者。我拿最高的 rnorm(1,m[1,1],sd[1,1]),rnorm(1,m[1,2],sd[1,2]),rnorm(1,m[1,3],sd [1,3]) 并存储它。我想模拟 1000 次并将结果存储为 跟随。 Output 我可以使用 Mapply 和 Sapply 的组合并进行复制吗?如果各位大神能指点一下,不胜感激。

means <- matrix(c(-0.086731728,-0.1556901,-0.744495,
          -0.166453802,       -0.1978284,         -0.9021422,
          -0.127376145,       -0.1227214,         -0.6926699
), ncol = 3)
m <- t(m)
colnames(m) <- c("inv1","inv2","inv3")
rownames(m) <- c("loan1","loan2","loan3")
sd <- matrix(c(0.4431459,              0.5252441,           0.5372112,
           0.4431882,          0.5252268,           0.5374614,
           0.4430836,          0.5248798,           0.536924
           ), ncol = 3)
sd <- t(sd)
colnames(sd) <- c("inv1","inv2","inv3")
rownames(sd) <- c("loan1","loan2","loan3")

【问题讨论】:

    标签: matrix simulation sapply mapply replicate


    【解决方案1】:

    鉴于这只是一个元素操作,您可以使用适当的矢量化函数来计算:

    # Create a function to perform the computation you want
    # Get the highest value from 1000 simulations
    f <- function(m,s,reps=1000) max(rnorm(reps,m,s))
    
    # Convert this function to a vectorised binary function
    `%f%` <- Vectorize(f)
    
    # Generate results - this will be a vector
    results <- means %f% sd
    
    # Tidy up results
    results <- matrix(results,ncol(means))
    colnames(results) <- colnames(means)
    rownames(results) <- rownames(means)
    
    # Results
    results
              inv1     inv2      inv3
    loan1 1.486830 1.317569 0.8679278
    loan2 1.212262 1.762396 0.7514182
    loan3 1.533593 1.461248 0.7539696
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 2020-08-25
      • 2020-05-14
      • 2012-02-11
      • 2011-04-24
      相关资源
      最近更新 更多