Calculate correlation of data generated by function in R

随声附和 提交于 2019-12-12 16:27:44

问题


I have created the following function in R:

timeseriesmodel <- function(N, x0, delta, variance) {
      z<-cumsum(rnorm(n=N, mean=0, sd=sqrt(variance)))
      t<-1:N
      x<-x0+t*delta+z
      return(x)}

This function returns a vector 'x' of length 'N', representing the data points of a random walk with drift.

In my case:

timeseriesmodel(250,1,0,1.2)

Now I should repeat this function 100 times, ending up with 100 timeseries data sets of length 250. Then I have to estimate the correlation between the 249th and 250th value of the dataset 'x', using the 100 sets.

As an inexperienced user of R, I don't see how to manipulate the data effectively and calculate/estimate the correlation of the requested data points. Help is very much appreciated.


回答1:


This is a work for replicate

> set.seed(1)
> Series <- replicate(100, timeseriesmodel(250,1,0,1.2) )  # repeating 100 times `timeseriesmodel`
> dim(Series)   # each result is store column-wise
[1] 250 100
> cor(Series[249,], Series[250,] ) # here's the correlation between element 249 and 250
[1] 0.9975532


来源:https://stackoverflow.com/questions/19162429/calculate-correlation-of-data-generated-by-function-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!