简体   繁体   中英

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. However, I want to use apply and replicate to carry out this calculation. 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

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. However, when I use the following code, I just get the same matrix, repeated 1000 times.

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

replicate repeats an expression. Once you assign your expression to the object matrixApply , replicate doesn't know how matrixApply was generated.
You want:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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