[R] How do I generate a random sample with an given variance?

Torsten Hothorn Torsten.Hothorn at rzmail.uni-erlangen.de
Tue Mar 27 12:52:23 CEST 2001


> pooh rondstr <poohtest at yahoo.com> writes:
> >Hi R gurus,
> >
> >
> >How do I generate a random sample with  a given
> >variance?
> 
> Form the standard normal ... for 100 numbers with a mean of 5 and a
> standard deviation of 2:
> 
>         rnorm(100, mean = 5, sd = 2)

hm, but 

R> x <- rnorm(100, mean = 5, sd = 2)
R> mean(x)
[1] 4.742486
R> var(x)
[1] 3.398248

is clearly not what one wants. Better:

R> x <- rnorm(100, mean = 5, sd = 2)
R> x <- (x - mean(x))/sqrt(var(x))
R> mean(x)
[1] 1.385177e-16
R> var(x)
[1] 1

and now create your sample with mean 5 and sd 2:

R> x <- x*2 + 5
R> mean(x)
[1] 5
R> var(x)
[1] 4

Torsten

> 
> Mark
> 
> 
> --
> Mark Myatt
> 
> 
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
> 

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list