1

I simulate with replicate() the distribution of the mean of ten numbers by repeating the operation five times.

> set.seed(123)
> z <- replicate(5, mean(rnorm(10))

I would like to create with sapply a second vector q such that

> identical(z, q)
[1] TRUE

Despite of the rich documentation in R Grouping functions: sapply vs. lapply vs. apply. vs. tapply vs. by vs. aggregate and in the help files, I fail to produce a code with sapply capable of integrate the five-times repetition that produced z. Indeed, the best result I got includes replicates() itself:

set.seed(123)
q <- sapply(replicate(5, rnorm(10)), mean)

and it produces a vector q of length 50, instead of a vector of length 5 as in z. I am afraid it is an egg of Columbus that I am looking from the wrong perspective.

Community
  • 1
  • 1
Worice
  • 3,847
  • 3
  • 28
  • 49
  • 4
    you want: `sapply(1:5, function(x) mean(rnorm(10)))` In this case, `replicate` will be a better choice – jeremycg Dec 29 '15 at 23:02
  • `apply(t(replicate(5, rnorm(10))), 1, mean)` – Dylan Dec 30 '15 at 04:01
  • Thank you @Jeremycg, it works. If I got the meaning of your function, it is equivalent to `sapply(1:5, function(x) {mean(rnorm(10))})`. May I ask why `replicate` is a better choice here? – Worice Dec 30 '15 at 09:39

0 Answers0