双循环不起作用

时间:2014-02-04 14:50:01

标签: r for-loop vector finance

我正在尝试基于规则创建一组新向量,用于向量列表。我的输入包含3个法线向量(indexrfreeret)和几个向量列表(roll),所有向量长度相同。我希望新的向量遵循规则:if index> roll - > ret,否则rfree,以便针对“k”个滚动向量计算索引,给出“k”个新向量,其仅包括ret和rfree输入。我当前的程序不起作用,我无法弄清楚原因。我得到的错误信息是

"Error in `*tmp*`[[j]] : subscript out of bounds"

但我无法弄清楚原因。任何帮助是极大的赞赏。

#Input:
roll <- list(runif(85),runif(85))
index <- runif(85)
rfree <- rnorm(85)
ret <- rnorm(85)

#Programe:
aret <- function(index, roll, ret, rfree, k=2){
  aret <- list()  
  for (j in seq(k))
    for (i in 1:length(ret)){
      if (roll[[j]][i]>index[i])(aret[[j]][i] <- ret[i])
      else(aret[[j]][i] <- rfree[i])
    }
}

1 个答案:

答案 0 :(得分:1)

这应该这样做,但我同意@Carl,如果所有向量长度相同,矩阵将更容易操作

roll <- matrix(runif(170),ncol=2) #lets use a matrix instead
index <- runif(85) #index is your indicator variable when compared to roll
rfree <- rnorm(85) #assign if roll>index
ret <- rnorm(85) #assign if index>roll

#use vector operations when possible, for speed and readability. Look into
#sapply, lapply etc. Apply is useful for column/row operations in matrices
result<-apply(roll,2, function(x){  
   # we will use an anonymous function here for this, 
   #but you could define elsewhere if needed
   w<-index>x  # where is index larger than our roll entries
   x[w]<-ret[w] #assign the corresponding ret there
   x[!w]<-rfree[!w] #assign the corresponding rfree where appropriate
   x
 })