我在时间序列对象上运行下面的代码时会得到NAs。实际上,我正在尝试使用扩展窗口对每列数据应用upDownCapture。我通过使用sapply和seq_along来实现这一点。
apply(data[,1:5],2, function(x) unlist(sapply(seq_along(x), function(i) upDownCapture(x[i:length(x)],idx[i:length(x)],12,'b'))))
,其中
upDownCapture <- function(y,x,minLen,upOrDown)
{
if(upOrDown == "u")
{
dataset <- na.omit(merge(x[x>0],y[x>0]))
} else if(upOrDown == "d"){
dataset <- na.omit(merge(x[x<0],y[x<0]))
} else dataset <- na.omit(merge(x,y))
## running a linear regression and getting slope
if(dim(dataset)[1] >= minLen){
slope <- lm(dataset[,2]~dataset[,1])$coefficients[[2]]
}else slope <- NA
return(slope)
}
我有类似的应用设置,例如下面,它们似乎工作正常
as.zoo(apply(excessReturns,2, function(x) {sapply(seq_along(x), function(i) sd(x[i:length(x)],na.rm = TRUE))}),order.by = index(data))
我无法理解应用于blueppcapture函数的sapply会丢失哪些信息。我在数据上运行了sapply和upDownCapture,它们似乎工作正常。
数据集看起来像
head(Data[,1])
A
1997-01-31 -0.0002
1997-02-28 -0.0428
1997-03-31 0.0827
1997-04-30 NA
1997-05-31 0.0351
1997-06-30 0.0749
head(idx)
Russell 1000
1997-01-31 0.00384
1997-02-28 -0.04504
1997-03-31 0.05411
1997-04-30 0.06404
1997-05-31 0.04144
1997-06-30 0.08183
感谢所有帮助。