Elle
Elle

Reputation: 97

generating simulated data in R with loop

I'm trying to simulate a data set that I will go on to using later. I need to create a variable with 1000 observations (n=1000) where each observation is a function of the previous observation with the following equation: yt is 80% yt-1 + 20% random noise with mean 0 and sd 1. Also, the value of y1 = 1.

This is the code I have so far (it runs, but only provides me with 1000 1's and no other values. Thus, it's not generating the data correctly and I cannot figure out why...):

n <- 1000
i <- rnorm(n=1000, mean=0, sd=1)
data <- rep(1,1000);
for(i in 2:1000){
  y[i]=0.80*y[i-1] + 0.20*rnorm(1)
    }
data

Any advice or help with this code is appreciated! Thanks!

Upvotes: 0

Views: 1395

Answers (2)

bgoldst
bgoldst

Reputation: 35314

Just to provide an alternative, you can use Rcpp to do this. Rcpp is often a good choice when you need to compute these kinds of sequences, since it is more favorable for performance to loop in compiled code, rather than in R code.

cppFunction('
    DoubleVector gensim(int n=1000, double mean=0, double sd=1 ) {
        DoubleVector res(n);
        double* resp = REAL(res);
        resp[0] = 1;
        for (int i = 1; i < n; ++i)
            resp[i] = 0.80*resp[i-1] + 0.20*Rf_rnorm(mean,sd);
        return res;
    }
');
gensim();
## [1]  1.0000000000  0.8083990372  0.6281932260  0.8158159737  0.4193451426
## [6]  0.2963336105  0.1500730564 -0.0251075339 -0.0990122044 -0.0497148910
## ...

Upvotes: 2

cr1msonB1ade
cr1msonB1ade

Reputation: 1716

You have not instantiated the y vector simply change data to y and you should be fine. Here is it all together:

y <- rep(1,1000);
for(i in 2:1000){
  y[i]=0.80*y[i-1] + 0.20*rnorm(1)
    }
y

Upvotes: 3

Related Questions