从列表中选择

时间:2012-10-08 18:17:02

标签: r list selection

我正在对金融时间序列进行一些分析,并使用函数acf()并将其应用于包含三个资产(VBLTX,FMAGX,SBUX)的回报的矩阵列,如下所示:

ret.acf<-apply(ret.mat, 2, acf, plot=FALSE)

现在,由于acf即使对于滞后0也返回相关系数,我想在所述滞后时消除结果。我做了:

ret.acf$VBLTX$acf[1]<-NA
ret.acf$FMAGX$acf[1]<-NA
ret.acf$SBUX$acf[1]<-NA

有更简单的方法吗?类似ret.acf$ALL$acf[1]<-NA

的内容

2 个答案:

答案 0 :(得分:2)

另一种方法是使用lapply

set.seed(001) # generating some data.
ts1 <- ts(rnorm(48), start=1, end=48, frequency=1)
ts2 <- ts(rnorm(48), start=1, end=48, frequency=1)
ts3 <- ts(rnorm(48), start=1, end=48, frequency=1)

DF <- data.frame(ts1, ts2, ts3)

ACF <- apply(DF, 2, acf, plot=FALSE) 
lapply(ACF, function(x) replace(x$acf, x$acf[1], NA)) # which produces...
$ts1
, , 1

               [,1]
 [1,]            NA
 [2,]  0.0401834301
 [3,] -0.1866931442
 [4,] -0.1225960706
 [5,]  0.0959013348
 [6,] -0.2063631992
 [7,] -0.2094716551
 [8,] -0.0003712424
 [9,]  0.0498757174
[10,] -0.0704899925
[11,]  0.1237808090
[12,]  0.2161029368
[13,] -0.0286315310
[14,] -0.0159506012
[15,]  0.1319491720
[16,] -0.1252024533
[17,] -0.1513954171


$ts2
, , 1

              [,1]
 [1,]           NA
 [2,] -0.096231670
 [3,]  0.081568099
 [4,] -0.087374506
 [5,] -0.177902683
 [6,]  0.100911018
 [7,] -0.035838433
 [8,]  0.127940241
 [9,]  0.001778011
[10,]  0.108459764
[11,]  0.064023572
[12,] -0.219530394
[13,] -0.088579334
[14,]  0.044634396
[15,] -0.092443901
[16,]  0.109249684
[17,] -0.196140673


$ts3
, , 1

             [,1]
 [1,]          NA
 [2,] -0.14669482
 [3,]  0.37416707
 [4,]  0.11488186
 [5,]  0.17975602
 [6,]  0.03751673
 [7,] -0.04159624
 [8,]  0.13195658
 [9,] -0.29795151
[10,]  0.12091659
[11,] -0.25545587
[12,] -0.04727648
[13,] -0.02498085
[14,]  0.03857024
[15,] -0.02722294
[16,] -0.02330514
[17,]  0.08765119

或者只是省略0阶的自相关

lapply(ACF, '[', 1:16)

$ts1

Autocorrelations of series ‘newX[, i]’, by lag

     1      2      3      4      5      6      7      8      9     10     11     12     13     14     15     16 
 0.040 -0.187 -0.123  0.096 -0.206 -0.209  0.000  0.050 -0.070  0.124  0.216 -0.029 -0.016  0.132 -0.125 -0.151 

$ts2

Autocorrelations of series ‘newX[, i]’, by lag

     1      2      3      4      5      6      7      8      9     10     11     12     13     14     15     16 
-0.096  0.082 -0.087 -0.178  0.101 -0.036  0.128  0.002  0.108  0.064 -0.220 -0.089  0.045 -0.092  0.109 -0.196 

$ts3

Autocorrelations of series ‘newX[, i]’, by lag

     1      2      3      4      5      6      7      8      9     10     11     12     13     14     15     16 
-0.147  0.374  0.115  0.180  0.038 -0.042  0.132 -0.298  0.121 -0.255 -0.047 -0.025  0.039 -0.027 -0.023  0.088 

答案 1 :(得分:1)

您可以使用元素for循环执行此操作:

for (col in names(ret.acf)) {
  ret.acf[[col]]$acf[1] <- NA
}