[R] Simulation

Spencer Graves spencer.graves at pdf.com
Tue Mar 18 17:09:56 CET 2003


Consider the following:

	p <- rbinom(40, 1, 0.9)
	e <- rnorm(40, 0, 1)
	if(any(p==0))e[p==0] <- 3*(rchisq(sum(p==0), 1)-1)

To find out whether this is faster than what you wrote, surround it with 
calls to proc.time, as follows:

  	start.time <- proc.time()
	p <- rbinom(40, 1, 0.9)
	e <- rnorm(40, 0, 1)
	if(any(p==0))e[p==0] <- 3*(rchisq(sum(p==0), 1)-1)
	(elapsed.time <- proc.time()-start.time)

I got 0.21 seconds for this.  Similarly,

  	start.time <- proc.time()
	p <- rbinom(40, 1, 0.9)
	e <- rnorm(40,0,1)*p + 3*(rchisq(40,1)-1)*(1-p)
	(elapsed.time <- proc.time()-start.time)

For this, I got 0.17 seconds.  Therefore, it looks like your is faster. 
  However, the technique I displayed above might be faster in crudely 
similar contexts.

Hope this helps.
Spencer Graves

Jacob van Wyk wrote:
> Hallo all users of R.
> I wish to simulate a simple linear regression, y=a+bx+e, (n=40, say),
> where x is
> N(0,1) and where
> e is N(0,1), with probability 0.9, and
> e is 3*(chisq(40,1)-1), say, with probability 0.1.
> For e: would the following work, or is there a better way?
> 
> p <- rbinom(40,1,0.9)
> e <- rnorm(40,0,1)*p + 3*(rchisq(40,1)-1)*(1-p)
> 
> Thanks for your time.
> Regards
> Jacob
> 
> 
> 
> Jacob L van Wyk
> Department of Mathematics and Statistics
> Rand Afrikaans University
> P O Box 524
> Auckland Park 2006
> South Africa
> Tel: +27-11-489-3080
> Fax: +27-11-489-2832
> 
> 
> ______________________________________
> 
> VRYWARING\ \ Die inhoud en enige aanhegsels van hierdie elektron... [[dropped]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help



More information about the R-help mailing list