Auburn
Auburn

Reputation: 61

R Loop random normal distribution

I'm trying to achieve the following: I want to generate 7 values from a normal distribution. Then I want to take these values, and using them as a mean generate 3 more (for each initial value) values from a normal distribution to replace them. I'd like to write this in a loop.

Let's use sd = 1.5 and sd = 0.7, and start with a mean of 0.

set.seed(1234)

mu.mat<-rnorm(7,mean=0,sd=1.5)

Gives me 7 nice values.

Then I want to create a number num [1:21] that generates 3 norm. distr. values using mean = first value of the just created list with sd = 0.7, three more using the second value and so on. Of the form:

rnorm(3,mean=mu.mat[1],sd=0.7)

Just for all entries in a loop.

What I've tried:

mu.mat2<-NULL
for(i in 1:7) {
  mu.mat2[i]<-rnorm(3,mean=mu.mat[i],sd=0.7)
}

Results in error: no. of items to replace is not a multiple of replacement length.

Any help on how to put this into a loop is very appreciated. Thanks in advance!

Upvotes: 2

Views: 914

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102920

Try replicate like below

> replicate(3,rnorm(length(mu.mat),mu.mat,0.7))
            [,1]        [,2]       [,3]
[1,] -2.19324092 -1.13895278 -2.1540788
[2,]  0.02102746  0.33894402  0.1077604
[3,]  1.00363528  1.26895511  1.9483744
[4,] -3.85258144 -4.15638335 -4.0041507
[5,] -0.05518348  0.05766686 -0.3700564
[6,]  0.21570611  2.45016846  1.1614128
[7,] -0.81698877 -0.76824819 -1.5786689

Upvotes: 1

Allan Cameron
Allan Cameron

Reputation: 174616

You don't need a loop. You can do:

rnorm(21, mean = rep(mu.mat, each = 3), sd = 0.7)
#>  [1] -0.4811184 -1.2327778 -1.8603816 -3.3073277 -2.5190560 -3.2298056
#>  [7] -2.3695570 -2.0228732 -1.1692489  2.0342910  1.0186855  1.0838678
#> [13]  0.5486730 -0.2439510 -0.1831147  2.2026024  0.1925301 -0.2153864
#> [19]  2.8944894  1.9213206  1.3804706

But the problem with your code is that you are trying to write three values (rnorm(3,mean=mu.mat[i],sd=0.7)) into a single atomic index mu.mat2[i]. It's not clear whether you were expecting a matrix as a result, but if so your loop would be:

mu.mat2 <- matrix(ncol = 3, nrow = 7)
for(i in 1:7) {
  mu.mat2[i,] <- rnorm(3, mean = mu.mat[i], sd = 0.7)
}

If you were wanting the result as a 7 x 3 matrix, you can do:

matrix(rnorm(21, mean = rep(mu.mat, each = 3), sd = 0.7), ncol = 3, byrow = TRUE)
#>             [,1]       [,2]       [,3]
#> [1,] -0.96624036 -1.4808460 -2.6824842
#> [2,] -2.88942108 -1.7299094 -3.0446737
#> [3,] -2.82034688 -0.9570087 -2.1822797
#> [4,]  0.58997289  1.0384926  1.8111506
#> [5,] -0.07705959 -0.1024418  0.7249310
#> [6,]  0.48851487  1.4729882  0.6496858
#> [7,]  1.47961292  1.5653253  2.0629409

Upvotes: 4

Related Questions