简体   繁体   English

使用循环在R中生成模拟数据

[英]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. 我需要创建一个具有1000个观测值(n = 1000)的变量,其中每个观测值都是使用以下公式得出的先前观测值的函数:yt是80%yt-1 + 20%随机噪声,均值为0和sd1。此外, 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...): 这是我到目前为止的代码(它可以运行,但是只为我提供1000 1,没有其他值。因此,它不能正确生成数据,而且我不知道为什么...):

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! 谢谢!

You have not instantiated the y vector simply change data to y and you should be fine. 您尚未实例化y向量,只需将data更改为y可以了。 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

Just to provide an alternative, you can use Rcpp to do this. 只是提供一种替代方法,您可以使用Rcpp做到这一点。 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. 当您需要计算这类序列时,Rcpp通常是一个不错的选择,因为在编译代码而不是R代码中循环执行对性能更有利。

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
## ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM