Home > other >  Storing data in inner loop r
Storing data in inner loop r

Time:04-28

I have a problem storing the data of my inner loop. The problem described here is simplified, to not get too specific.

I have a database (df) that consists of 2 years. I splited those 2 years a <- split(df,df$year). I now need to make a monthly calculation. Therefore I used a new loop. To store my results I used excRet <- rep (0,24). The loops work,however I'm only able to see the last output. The inner loop overwrites the first results. I'm sure there is a better way to store my data. Unfortunately, I'm quite new to R and programming in general.

for (i in 1:2) {
  year <- a[[`i`]]
 
  #split the year into 12 months
  spm <- split(year, year$Month)
  
  for (j in 1:12) {
    b <- spm[[`j`]]

    exrt <- mean(b$excessReturn)
    excRet [j] <- exrt

    j = j   1
  }
  
  i= i 1

}

(Just calculating from the months is not possible as there're a bit more selection criteria in the inner loop. I left these out to not overcomplicate the question. The loops work fine, storing the data from the inner loop is the problem)

CodePudding user response:

Waru, its a little tough without a reproducible example. Here is a simple one using mtcars, showing how to loop across two different indices. If this doesn't fit, trying using dput with a sample of your actual data.

outer<- NULL

for( i in 1:5){
  inner <- NULL
  
  for( j in 1:5){
    
  a <- mean( mtcars[ i, j  ])  
   
  inner <- cbind( inner , a ) 
    
  }
  
  outer <- rbind( outer , inner)
  
}


print( outer )
  • Related