1

我正在尝试使用以下代码确定日期在矩阵中的位置:

#portret is a list of daily returns for three different stocks from 1980-01-01 to 2010-12
#13.These dates are listed in the first column of the portret data frame
library(quantmod)
library(FRAPO)
getSymbols(c("F","AA","IBM"),from="1980-01-01", to="2010-12-31")
port=cbind(F$F.Adjusted,AA$AA.Adjusted,IBM$IBM.Adjusted)
portret=returnseries(port,"discrete",trim=TRUE)
portret=data.frame(index(portret),coredata=portret)
date.list=seq.Date(as.Date("1990-10-01"),as.Date("2010-10-01"),by="month")
length(date.list)
#this equals 241
date.index=matrix(0,241,2)
for(i in 1:241){
    date.index[i,]=which(portret[,1]==as.character(date.list[i]),arr.ind=TRUE)}

我不断收到此错误:替换的长度为零

请指教。

4

1 回答 1

0

错误是因为条件语句评估为FALSE.

IE:

  x      <- 1:5
  x[[2]] <- which(FALSE) 

问题是并非所有日期date.list都在portret[, 1].
相反,在你的for循环中试试这个:

w <- which(portret[,1]==as.character(date.list[i]),arr.ind=TRUE)
date.index[i,] <- ifelse(identical(w, integer(0)), c(NA, NA), w)

但更好的是:

date.index <- 
  sapply(as.character(date.list), function(D) 
      {w <- which(portret[,1]==D, arr.ind=TRUE);
      ifelse(identical(w, integer(0)), c(NA, NA), w)})
于 2013-04-23T04:12:19.757 回答