24

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?

epo3
  • 2,991
  • 2
  • 33
  • 60
BBSysDyn
  • 4,389
  • 8
  • 48
  • 63

2 Answers2

22

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].

csgillespie
  • 59,189
  • 14
  • 150
  • 185
  • Can we use rnorm(100) or something similar to create values only between 0 and 1? currently it gives values between (-1 to 1) – Mona Jalal Feb 15 '14 at 21:18
5

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?