Wave
Wave

Reputation: 1266

calling rnorm with a matrix of means and a matrix of standard deviations

I have two matrices of dimension n*p, one containing means and one containing sds.

I want to do something like rnorm(1, means, sds) and get a new matrix n*p so that each cell results from rnorm(1, means[i,j], sds[i,j]).

How do I do this without looping?

I looked at functions from the apply family, sweep and outer, but despite the solution probably being a simple one-liner, I can't figure it out.

means=matrix(1:12,ncol=4)
sds=round(matrix(runif(12,0.1,0.2),ncol=4),2)

Upvotes: 1

Views: 960

Answers (1)

jogo
jogo

Reputation: 12569

The function rnorm() can take a vector in the parameter mean= and a vector in the parameter sd= as you want:

matrix(rnorm(length(means), mean=means, sd=sds), nrow(means))

If you already have a matrix m with the right dimensions then you can do:

m[] <- rnorm(length(means), mean=means, sd=sds)

(thx to @BenBolker for the comment)

Upvotes: 2

Related Questions