width=20
前几 (3) 个窗口中的某些列完全缺失 ,因此出现错误
data(managers)
class(managers) # [1] "xts" "zoo"
class(managers$HAM4) # [1] "xts" "zoo"
var2<-rollapply(managers,width=20,FUN=function(x) VaR(R=x,p=.95,method="modified"),by.column=TRUE)
使用traceback
,您可以检查可能的错误来源,请注意第 12 步na.omit(x)
,请参阅?na.omit
traceback()
#17: as.matrix.xts(x)
#16: as.matrix(x)
#15: as.vector(as.matrix(x), mode = mode)
#14: as.vector.zoo(x, mode)
#13: as.vector(x, mode)
#12: as.vector(na.omit(R[, column]))
#11: VaR.CornishFisher(R = R, p = p)
#10: VaR(R = managers, p = 0.95, method = "modified") at #1
#9: FUN(.subset_xts(data, (i - width + 1):i, j), ...)
#8: FUN(newX[, i], ...)
#7: apply(ind, 1, function(i) FUN(.subset_xts(data, (i - width +
# 1):i, j), ...))
#6: FUN(1:10[[5L]], ...)
#5: lapply(X = X, FUN = FUN, ...)
#4: sapply(1:NCOL(data), function(j) apply(ind, 1, function(i) FUN(.subset_xts(data,
# (i - width + 1):i, j), ...)))
#3: xts(sapply(1:NCOL(data), function(j) apply(ind, 1, function(i) FUN(.subset_xts(data,
# (i - width + 1):i, j), ...))), tt, if (by == 1) attr(data,
# "frequency"))
#2: rollapply.xts(managers, width = 20, FUN = function(managers) VaR(R = managers,
# p = 0.95, method = "modified"), by.column = TRUE)
#1: rollapply(managers, width = 20, FUN = function(managers) VaR(R = managers,
# p = 0.95, method = "modified"), by.column = TRUE)
#
对于您的第一个窗口 = 20(实际上大约 60 个)观察,HAM5、HAM6 列完全丢失,这些导致步骤 12 中的数据为空。
head(managers,20)
#Empty data since NA columns are omitted see step 12 above.
na.omit(head(managers,20))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#>
数据中没有缺失值edhec
,因此没有问题
any(is.na(edhec))
any(is.na(managers))
一种更简单的方法是保留没有任何缺失值的行并计算它们的统计信息
managers_sub = managers[complete.cases(managers),]
var3<-rollapply(managers_sub,width=20,FUN=function(x) VaR(R=x,p=.95,method="modified"),by.column=TRUE)
或者
You could find the index where none of the columns are completely missing and subset accordingly
sapply(colnames(managers),function(x) all(is.na(managers[60:80,x])))