Radda
Radda

Reputation: 51

Calculate correlation of data generated by function in R

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.

Upvotes: 3

Views: 1310

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61214

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

Upvotes: 1

Related Questions