我在处理 xts 对象列表时遇到问题。在列表元素上运行时,我会遇到不同且奇怪的行为lapply
,有时还会出现程序段错误。我在 Ubuntu 9.10 上运行 R 2.12.2,尽管我在 Windows XP 上运行 2.13.1 时遇到了类似的问题。
我正在尝试将包含季度财务数据的数据框拆分为多个时间序列。我在 CIK 代码上拆分数据帧,这是一个整数。数据框是:
> head(CQ[,c("datadate","fqtr","cik","ibq","mkvaltq","prccq","sic")])
datadate fqtr cik ibq mkvaltq prccq sic
3 2009-12-31 1 61478 3.400 601.12800 6.21 3661
4 2010-03-31 2 61478 -13.000 709.07000 7.31 3661
5 2010-06-30 3 61478 75.900 718.77000 7.41 3661
6 2010-09-30 4 61478 10.900 1231.52400 12.67 3661
7 2004-03-31 3 319126 0.424 9.73455 1.05 3861
8 2004-06-30 4 319126 0.407 13.90650 1.50 3861
...
我用来创建 xts 对象列表的代码是:
CQT<-by(CQ[c("datadate","ibq","cik","mkvaltq","prccq","sic","fqtr")],CQ$cik,function(x)
{
xts(x,order.by=x$datadate,frequency=4)
}
)
CQT<-as.list(CQT)
我不确定转换为列表是否绝对必要,但我对列表感到满意。
这将创建以下数据结构,这对我来说似乎是正确的:
> head(CQT)
$`20`
datadate ibq cik mkvaltq prccq sic fqtr
2004-03-31 "2004-03-31" "1.422" "20" " 53.75880" " 21.8000" "3823" "1"
2004-06-30 "2004-06-30" "1.389" "20" " 55.04400" " 22.0000" "3823" "2"
2004-09-30 "2004-09-30" "1.562" "20" " 55.69816" " 22.1200" "3823" "3"
2004-12-31 "2004-12-31" "2.237" "20" " 67.11840" " 26.5500" "3823" "4"
2005-03-31 "2005-03-31" "1.643" "20" " 77.28716" " 30.4400" "3823" "1"
2005-06-30 "2005-06-30" "1.916" "20" " 75.12520" " 29.3000" "3823" "2"
...
当我尝试lapply
在CQT
. 在多次遇到问题后,我将测试代码压缩为:
lapply(CQT,function(x) {
lag.xts(x[,"prccq"],1)
}
)
我想如果我能做到这一点,那么我可能走在正确的轨道上。
此代码有时只会出现段错误。例如,在我运行的最近一次迭代中(出于发布的目的),代码可以很好地通过许多记录。例如:
$`6494`
prccq
2004-03-31 NA
2004-06-30 "0.240"
2004-09-30 "0.150"
2004-12-31 "0.090"
2005-03-31 "0.062"
...
但是,它会抛出:
$`6720`
Error in vector(storage.mode(x)) :
vector: cannot make a vector of mode 'NULL'.
这并不总是错误的:有时我会收到关于角色或其他东西的抱怨,而且它从来没有在同一个记录上停止过两次。此特定记录似乎没有任何问题:
> CQT$"6720"
datadate ibq cik mkvaltq prccq sic fqtr
2004-03-31 "2004-03-31" " 10.740" "6720" "559.8638" "16.03" "3949" "1"
2004-06-30 "2004-06-30" " 6.178" "6720" "558.6060" "15.70" "3949" "2"
2004-09-30 "2004-09-30" " 13.198" "6720" "667.6474" "14.31" "3949" "3"
2004-12-31 "2004-12-31" " 8.825" "6720" "743.1205" "15.88" "3949" "4"
2005-03-31 "2005-03-31" " 2.324" "6720" "643.6650" "13.75" "3949" "1"
2005-06-30 "2005-06-30" " 1.453" "6720" "594.0200" "12.68" "3949" "2"
2005-09-30 "2005-09-30" " 16.740" "6720" "534.5802" "11.40" "3949" "3"
2005-12-31 "2005-12-31" "-232.078" "6720" "474.1590" "10.11" "3949" "4"
2006-03-31 "2006-03-31" " 3.642" "6720" "589.5614" "12.55" "3949" "1"
2006-06-30 "2006-06-30" " 2.143" "6720" "514.9567" "10.94" "3949" "2"
2006-09-30 "2006-09-30" " 21.518" "6720" "552.9757" "11.73" "3949" "3"
2006-12-31 "2006-12-31" " 10.385" "6720" "651.7707" "13.19" "3949" "4"
2007-03-31 "2007-03-31" " 4.767" "6720" "597.7659" "12.09" "3949" "1"
我对此束手无策。我不确定我的编码是否不正确(我找不到使用 xts 对象列表的好例子),或者我的 xts 包是否有问题。我已经通过删除包然后使用 R-Forge 存储库重新安装来重新安装 xts,所以我应该拥有最新版本。
如果我可以提供任何其他信息,请告诉我。