Niko24
Niko24

Reputation: 81

Saving values of ACF in R for a plot

I need to make a plot of several ACFs together, but I am not quite sure on how to 'save' the values of each ACF and approach them again later on.

This is what I have done so far:

#Simulating 
n <- 1000
Y <- c()
ACF <- c()

for (i in 1:10) {
  eps <- rnorm(n, mean = 0, sd = sqrt(2)^0.5)
  Y <- cbind(Y, 1/4 + cumsum(eps))
  X <- acf(Y, lag.max = 100, plot = FALSE)
  ACF <- cbind(ACF, X)
}

#Plotting
plot(0,0, xlim=c(0,100), ylim=c(0,1), xlab="Lags ", ylab="ACF")
for(i in 1:10){
  lines(ACF[,i],col=cl[i])
}

but it is not working, so I hope that someone can help me with what I should do.

Upvotes: 0

Views: 1084

Answers (1)

Sathish
Sathish

Reputation: 12713

Create a function myfun that returns simulated acf and lag values. Then using sapply loop through 1:10 and get the simulated acf and lag values into matrix. Now using base plot function, draw the figure.

myfun <- function( x )
{
  n <- 1000
  eps <- rnorm(n, mean = 0, sd = sqrt(2)^0.5)
  eps <- 1/4 + cumsum(eps)
  ACF <- acf(eps, lag.max = 100, plot = FALSE)  # compute acf
  return( list( acf = ACF[['acf']],        # returns acf
                lags = ACF[['lag']] ) )    # returns lag
}

ACF <- sapply(1:10, myfun)   # loop through 1:10 and get acf and lag values

ACF
# [,1]        [,2]        [,3]        [,4]        [,5]        [,6]        [,7]       
# acf  Numeric,101 Numeric,101 Numeric,101 Numeric,101 Numeric,101 Numeric,101 Numeric,101
# lags Numeric,101 Numeric,101 Numeric,101 Numeric,101 Numeric,101 Numeric,101 Numeric,101
# [,8]        [,9]        [,10]      
# acf  Numeric,101 Numeric,101 Numeric,101
# lags Numeric,101 Numeric,101 Numeric,101


# using base plot function
plot(NA, xlim=c(0,100), ylim=c(0,1), xlab="Lags ", ylab="ACF")
for(i in 1:10){
  lines( x = unlist(ACF[ 'lags', i ]), y = unlist( ACF[ 'acf',  i ] ), col= rainbow(10)[i])
}

enter image description here

Upvotes: 3

Related Questions