[R] help with simulate AR(1) data

Rolf Turner r.turner at auckland.ac.nz
Tue Jul 22 22:37:21 CEST 2008


On 23/07/2008, at 7:52 AM, cathelf wrote:

>
> Hi, sorry for bothering your guys again.
> I want to simulate 100 AR(1) data with cor(x_t, x_t-1)=rho=0.3. The  
> mean of
> the first 70 data (x_1 to x_70) is 0 and the mean of the last 30  
> data (x_71
> to x_100) is 2. Can I do it in the following way?
>
> x <- arima.sim(list=(ar=0.3), 100)
> mean <- c(rep(0, 70), rep(2, 30))
> xnew <- x+mean
>
>
> If the above code to simulate 100 AR(1) data is right, what should  
> I do if I
> want to simulate 1000 independent group of this data? Each group  
> contains
> 100 AR(1) data. So it is a matrix of 1000*100. Each row is a AR(1).  
> I think
> there should be a quicker way to do that? (the easies way is  
> simulate ar(1)
> 1000 times, but it waste time, I think).

	What else can you do?  To simulate 1000 independent realizations
	of an AR(1) process you need to, uh, simulate 1000 independent
	realizations of an AR(1) process.  Like.

	For compact ***code*** you could write something like:

	junk <- matrix(unlist(lapply(1:1000,function(x){arima.sim(list 
(ar=0.3),100)+mean})),nrow=1000,byrow=TRUE)

	(as long as ``mean'' is there in your global workspace).

	This took 0.619 seconds on my Imac; not too much time wasted.

	But by turning your results into a matrix, you lose the time series
	attributes of your simulated series.  Are you sure you need a matrix?
	You could simply create a *list* of length 1000, each entry of which
	is a realization of an AR(1) process.  Just by doing:

	junk <- lapply(1:1000,function(x){arima.sim(list(ar=0.3),100)+mean}))

	Each entry of junk will be an object of class "ts" --- which might be
	a Good Thing.

		cheers,

			Rolf Turner

	

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}



More information about the R-help mailing list