通过循环索引日期

时间:2013-04-23 03:36:32

标签: r loops for-loop indexing

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

#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)}

我一直收到这个错误:   替换的长度为零

请指教。

1 个答案:

答案 0 :(得分:0)

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

即:

  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)})