2017-03-06 63 views
0

我需要将几个ACF放在一起,但我不太清楚如何“保存”每个ACF的值并稍后再接近它们。将ACF的值保存在R中作为一个阴谋

这是我迄今所做的:

#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]) 
} 

,但它是不工作的,所以我希望有人能帮助我,我应该做的。

+0

你的意思是在Y中运行ACF其中Y是矩阵? –

回答

2

创建函数myfun,返回模拟的acflag值。然后使用sapply循环通过1:10,并将模拟的acflag值得到矩阵。现在使用基地plot功能,画出图。

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

+0

@ Niko24删除了'matplot',并且根据每个问题只使用了基本的'plot'。这一次,从'myfun'获得滞后值以及acf值 – Sathish