Search code examples
rfor-loopnested-loops

Nested Loop - subscript out of bounds error


Example:


set.seed(1)
data1 <- as.data.frame(matrix(runif(n=10, min =-0.01, max=0.01), nrow =100, ncol =5))
data2 <- as.data.frame(matrix(runif(n=10, min =-0.01, max=0.01), nrow =100, ncol =5))
data3 <- as.data.frame(matrix(runif(n=10, min =-0.01, max=0.01), nrow =100, ncol =5))
data4 <- as.data.frame(matrix(runif(n=10, min =-0.01, max=0.01), nrow =100, ncol =5))
data5 <- as.data.frame(matrix(runif(n=10, min =-0.01, max=0.01), nrow =100, ncol =5))

rolling_window_set <-c(12,36,60) #Adding 12m / 36m and 60m time periods #Improve code in this section
data_period_window <-c()
my_list <- list(data1,data2,data3,data4,data5)
for(j in 1:length(rolling_window_set)) {
  for (i in 1:length(my_list)) {
    data_period_window[[j]][[i]] = my_list[[i]][(nrow(my_list[[i]])-rolling_window_set[[j]]+1):nrow(my_list[[i]]), ]
  }
}

My goal is to create a list with 5 components in each layer. [[1]][[1]], [[1]][[2]]... [[1]][[5]]....[[2]][[1]]...[[2]][[5]]....[[3]][[1]] to [[3]][[5]]. List 1 output should be a dataframe with ncol = 12, list 2 should be dataframes with ncol = 36 and list 3 with ncol = 60.

I get a subscript out of bounds error. I'm sure this relates to the nested loop structure, but really not sure how to fix.


Solution

  • You are trying to access an element which does not exist. Extend the list inside the loop and it will work.

    set.seed(1)
    data1 <- as.data.frame(matrix(runif(n=10, min =-0.01, max=0.01), nrow =100, ncol =5))
    data2 <- as.data.frame(matrix(runif(n=10, min =-0.01, max=0.01), nrow =100, ncol =5))
    data3 <- as.data.frame(matrix(runif(n=10, min =-0.01, max=0.01), nrow =100, ncol =5))
    data4 <- as.data.frame(matrix(runif(n=10, min =-0.01, max=0.01), nrow =100, ncol =5))
    data5 <- as.data.frame(matrix(runif(n=10, min =-0.01, max=0.01), nrow =100, ncol =5))
    
    rolling_window_set <-c(12,36,60) #Adding 12m / 36m and 60m time periods #Improve code in this section
    data_period_window <- c()
    my_list <- list(data1,data2,data3,data4,data5)
    for(j in 1:length(rolling_window_set)) {
        data_period_window[[j]] <- list(NA)
        for (i in 1:length(my_list)) {
            data_period_window[[j]][[i]] = my_list[[i]][(nrow(my_list[[i]])-rolling_window_set[[j]]+1):nrow(my_list[[i]]), ]
        }
    }