Reputation: 1
Is there any way in R, other than with loops, to create a matrix using different means and standard deviations for the matrix's columns?
For example, I want to create a 3x4 matrix representing 3 points with 4 attributes each, such that every column (every attribute) has its own mean and sd.
Upvotes: 0
Views: 66
Reputation: 57686
Yes, you can do without loops. Take advantage of the fact that matrices in R are stored in column-major order, and replicate the mean and sd vectors to match.
means <- c(1, 10, 100, 1000)
sds <- c(0.1, 1, 10, 100)
rows <- 3
cols <- 4
m <- matrix(rnorm(rows*cols, m=rep(means, each=rows), s=rep(sds, each=rows)),
rows, cols)
m
[,1] [,2] [,3] [,4]
[1,] 0.9993278 11.694798 105.53191 841.2182
[2,] 0.8945916 9.556729 92.90462 1212.6817
[3,] 0.9889313 10.088022 113.67009 991.2138
Upvotes: 1
Reputation: 6118
I am not sure what you are looking for but this might help:
matrix(c(x = rnorm(n=3,mean=0.5,1),
y = rnorm(n=3,mean=2, 4),
z = rnorm(n=3, mean=3.5, 10),
a= rnorm(n=3,mean=5,12)),nrow=3,ncol=4)
[,1] [,2] [,3] [,4]
[1,] 0.7876793 2.9456827 8.082376 -3.065875
[2,] -0.9956971 4.2766553 14.178532 -5.003888
[3,] 2.1224071 0.7110594 6.744876 -11.006110
Note: you might bet different results as the data is randomly generated. Each column has its own mean and standard deviation.
Upvotes: 0