Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling rnorm with a vector of means

When I call rnorm passing a single value as mean, it's obvious what happens: a value is generated from Normal(10,1).

y <- rnorm(20, mean=10, sd=1)

But, I see examples of a whole vector being passed to rnorm (or rcauchy, etc..); in this case, I am not sure what the R machinery really does. For example:

a = c(10,22,33,44,5,10,30,22,100,45,97)
y <- rnorm(a, mean=a, sd=1)

Any ideas?

like image 681
BBSysDyn Avatar asked Aug 18 '10 09:08

BBSysDyn


2 Answers

The number of random numbers rnorm generates equals the length of a. From ?rnorm:

n: number of observations. If ‘length(n) > 1’, the length is taken to be the number required.

To see what is happening when a is passed to the mean argument, it's easier if we change the example:

a = c(0, 10, 100)
y = rnorm(a, mean=a, sd=1)
[1] -0.4853138  9.3630421 99.7536461

So we generate length(a) random numbers with mean a[i].

like image 89
csgillespie Avatar answered Nov 12 '22 14:11

csgillespie


a better example:

a <- c(0,10,100)
b <- c(2,4,6)
y <- rnorm(6,a,b)
y

result

[1]  -1.2261425  10.1596462 103.3857481  -0.7260817   7.0812499  97.8964131

as you can see, for the first and fourth element of y, rnorm takes the first element of a as the mean and the first element of b as the sd.

For the second and fifth element of y, rnorm takes the second element of a as the mean and the second element of b as the sd.

For the third and sixth element of y, rnorm takes the third element of a as the mean and the third element of b as the sd.

you can experiment with diferent number in the first argument of rnorm to see what is happening

For example, what is happening if you use 5 instead 6 as the first argument in calling rnorm?

like image 39
Francisco Velez Avatar answered Nov 12 '22 16:11

Francisco Velez