1
我正在研究R代码以实现各种美国国债的收益率曲线。这里是我的代码:(问题语句遵循的代码结束)R中对于相同xts,非递归对象的不同处理
library(quantmod)
t3mo=getSymbols("DGS3MO",src="FRED",auto.assign = FALSE)
t6mo=getSymbols("DGS6MO",src="FRED",auto.assign = FALSE)
t1yr=getSymbols("DGS1",src="FRED",auto.assign = FALSE)
t2yr=getSymbols("DGS2",src="FRED",auto.assign = FALSE)
t3yr=getSymbols("DGS3",src="FRED",auto.assign = FALSE)
t5yr=getSymbols("DGS5",src="FRED",auto.assign = FALSE)
t7yr=getSymbols("DGS7",src="FRED",auto.assign = FALSE)
t10yr=getSymbols("DGS10",src="FRED",auto.assign = FALSE)
t20yr=getSymbols("DGS20",src="FRED",auto.assign = FALSE)
t30yr=getSymbols("DGS30",src="FRED",auto.assign = FALSE)
# Combine the yield data into one object
treasury=merge(t3mo ,t6mo ,t1yr ,t2yr ,t3yr ,t5yr ,t7yr ,t10y) ,t20yr ,t30yr)
treasury[c(1:3,nrow(treasury)),]
# subset to include the yield from 1990-2013
extreme=subset(treasury, index(treasury)>="1990-01-01" & index(treasury)<="2013-12-31")
extreme=extreme[,c(1,8,10)]
extreme=na.omit(extreme)
# Identify examples of different shapes of the yield curve
extreme$sign.diff=extreme$DGS30-extreme$DGS3MO
extreme$inverted=ifelse(extreme$sign.diff==min(extreme$sign.diff),1,0)
# inverted: 30 year yield<3 month yield
inverted=subset(extreme,extreme$inverted==1)
extreme$upward=ifelse(extreme$sign.diff==max(extreme$sign.diff),1,0)
# upward normal: 30 year yield>3 month yield
upward=subset(extreme,extreme$upward==1)
extreme$abs.diff=abs(extreme$DGS30 - extreme$DGS3MO)
extreme$flat=ifelse(extreme$abs.diff==min(extreme$abs.diff),1,0)
# maybe the flat yield curve or the humpback yield curve
flat=subset(extreme,extreme$flat==1)
# compare 30-year yield to 10-year yield to find
# the flattest curves within the set of flat curves above
flat$abs.diff2=abs(flat$DGS30-flat$DGS10)
flat$flat2=ifelse(flat$abs.diff2==min(flat$abs.diff2),1,0)
flat$flat2==1
# WHY DOES THIS NOT WORK, GIVEN "flat" IS THE SAME AS THE VARIABLE "extreme"???**
flat2=subset(flat,flat$flat2==1)
class(flat); class(extreme)
is.recursive(extreme)
is.recursive(flat)
这里的问题是:extreme
是XTS和原子(不递归)。 flat
是extreme
的子集。 flat
也是一个xts和原子(不递归)。我可以使用$
运算符访问extreme
和flat
中的列。然而,虽然我可以使用$
操作者子集extreme
,我不能flat
这样做和R返回错误消息为:在平板$ flat2
错误:$操作者是无效的原子矢量
我不知道为什么R陈述这个错误。 flat$flat2==1
独立工作,但在站在subset()
功能时不工作? R做了不同的治疗?
谢谢你很多的帮助,Ulrich。现在我明白了原因。你的代码对我来说也是一个很好的学习范例。最好。 – JimTran