TMOTTM - 11 months ago 47

R Question

How do I provide a vector to the

`mean`

`rnorm`

`around_int1_mean <- seq(1.5, 3.5, 0.1)`

I would like to do something like

`rnorm(n=25, mean=around_int1_mean, sd=0.2)`

`for`

I want to get

`length(around_int1_mean)`

`n=25`

Answer

I want to get

`length(around_int1_mean)`

sets of samples with`n=25`

with mean (in the first set) of 1.5, then 1.6 and so on until the last set has mean 3.5. So in the end I'd get 21 sets of samples of size 25.

You need

```
rnorm(n = length(around_int1_mean) * 25,
mean = rep(around_int1_mean, each = 25), sd = 0.2)
```

The `mean`

and `sd`

argument in `rnorm`

are vectorized. They would first be recycled to have length `n`

. Then, for `i = 1, 2, ..., n`

, the `i-th`

sample is drawn from `N(mean[i], sd[i])`

.

As another example, if you want a single sample for each mean, do:

```
rnorm(n = length(around_int1_mean), mean = around_int1_mean, sd = 0.2)
```

**As @TMOTTM insists I am wrong and voted down my answer, I must show evidence to defend myself.**

```
around_int1_mean <- seq(1.5, 3.5, by = 0.1)
```

I would set `sd = 0`

to eliminate randomness, so random samples will just take `mean`

value with probability of 1. This enables us to prove that `rnorm`

is generating correct set of samples for correct `mean`

.

```
x <- rnorm(n = length(around_int1_mean) * 25,
mean = rep(around_int1_mean, each = 25), sd = 0)
```

Also, I would use a matrix to demonstrate it:

```
matrix(x, nrow = 25)
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13]
# [1,] 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7
# [2,] 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7
# [3,] 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7
# [4,] 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7
# [5,] 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7
# [6,] 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7
# [7,] 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7
# [8,] 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7
# [9,] 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7
# [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21]
# [1,] 2.8 2.9 3 3.1 3.2 3.3 3.4 3.5
# [2,] 2.8 2.9 3 3.1 3.2 3.3 3.4 3.5
# [3,] 2.8 2.9 3 3.1 3.2 3.3 3.4 3.5
# [4,] 2.8 2.9 3 3.1 3.2 3.3 3.4 3.5
# [5,] 2.8 2.9 3 3.1 3.2 3.3 3.4 3.5
# [6,] 2.8 2.9 3 3.1 3.2 3.3 3.4 3.5
# [7,] 2.8 2.9 3 3.1 3.2 3.3 3.4 3.5
# [8,] 2.8 2.9 3 3.1 3.2 3.3 3.4 3.5
# [9,] 2.8 2.9 3 3.1 3.2 3.3 3.4 3.5
# [ reached getOption("max.print") -- omitted 16 rows ]
```

Obviously my answer is correct. Each column has 25 samples with the same mean.

Source (Stackoverflow)