PythonSOS
PythonSOS

Reputation: 359

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)

Upvotes: 0

Views: 59

Answers (1)

Brian Montgomery
Brian Montgomery

Reputation: 2414

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)

Upvotes: 1

Related Questions