简体   繁体   English

对矩阵使用 function 中的应用和复制

[英]Use Apply and Replicate in a function for a matrix

I have a N x N numeric matrix that I converted into a data frame in R, and I need to apply rnorm to each cell.我有一个 N x N 数值矩阵,我将它转换为 R 中的数据框,我需要将rnorm应用于每个单元格。 However, I want to use apply and replicate to carry out this calculation.但是,我想使用applyreplicate来执行这个计算。 My current code for the calculation in the first cell (that has headers) is:我当前在第一个单元格(具有标题)中的计算代码是:

firstCell <- data.frame(
    rnorm(1000, mean = matrixName[2,1], sd = 0.8*matrixName[2,1])
)

I tried using apply first with我尝试先使用apply

matrixApply <- apply(
    matrixName, c(1,2), function(x) rnorm(
        1000, 
        mean = x, 
        sd = 0.8*x
    )
)

Now, I want to use replicate to replicate this same calculation 1000 times, resulting in 1000 instances of this N x N matrix.现在,我想使用replicate来复制同样的计算 1000 次,从而得到这个 N x N 矩阵的 1000 个实例。 However, when I use the following code, I just get the same matrix, repeated 1000 times.但是,当我使用以下代码时,我只是得到相同的矩阵,重复 1000 次。

useReplicate <- replicate(n=1000, matrixApply, simplify=F)

replicate repeats an expression. replicate重复一个表达式。 Once you assign your expression to the object matrixApply , replicate doesn't know how matrixApply was generated.将表达式分配给 object matrixApply ,replicate 不知道matrixApply是如何生成的。
You want:你要:

useReplicate <- replicate(n=1000, apply(
    matrixName, c(1,2), function(x) rnorm(
        1000, 
        mean = x, 
        sd = 0.8*x
    )
), simplify=F)

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

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