Question

I am trying to create a set of new vectors based on a rule, for a list of vectors. My input consists of 3 normal vectors (index, rfree, ret) and a list of several vectors (roll), all vectors being the same length. I want the new vectors to follow the rule: if index>roll -> ret, else rfree, so that the index is evaluated against the "k" number of roll vectors giving "k" new vectors that only consist of ret and rfree inputs. My current program doesn't work and I can't figure out why. The error message I get is

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

But I can't really figure out why. Any help is greatly appreciated.

#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])
    }
}
Was it helpful?

Solution

This should do it, but I agree with @Carl, a matrix will be easier to manipulate here if all vectors are the same length

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
 })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top