0

In a first large Loop I generated 1,000,000 matrices XY_1_1, ..., XY_1000_1000:

for (i in 1:1000){
   for (j in 1:1000){
        assign(paste0("XY",i,j ,sep='_'), matrix(ncol=10, nrow=4))
   }
}

Now I want to assign different outcomes of a function (vector of length 10) to the rth row of the matrices, which should somehow like this:

for (r in 1:4){
  for (i in 1000){
    for (j in 1:1000){
       assign(paste0("XY",i,j ,sep='_')[r,], function(i,j,r))
    }
  }
}

Unfortunately, I get the error 'incorrect number of dimensions'. Furthermore, I tried using the get()-Function:

for (r in 1:4){
  for (i in 1000){
    for (j in 1:1000){
       get(paste0("XY",i,j ,sep='_'))[r,] <-  function(i,j,r)
    }
  }
}

which brought the error 'target of assignment expands to non-language object'. Does anyone know a proper solution? Let me know in case you need further information.

Julia236
  • 11
  • 5

1 Answers1

2

Consider saving all objects into a list using lapply especially since they are the same structure. With this approach, you avoid millions of matrices flooding your global environment becoming a management headache! Plus, you can easily run the same operations like the rth row across all matrix elements. Additionally, you avoid nested for loops or using assign and get and eval(parse(paste...))). And then you still can get those million objects from list, using list2env:

# LIST OF A MILLION MATRICES (SAME DIMS) 
matlist <- lapply(seq(1000000), function(i) matrix(ncol=10, nrow=4))

# NAMING LIST ITEMS
itemnames <- paste0("XY", c(outer(seq(1000), seq(1000), paste0)))
matlist <- setNames(matlist, itemnames)

# UPDATING MATRIX
matlist <- setNames(lapply(seq(length(matlist)), function(i){        
    mat <- matlist[[i]]
    for (r in seq(4)) {
        mat[r,] <- some_function(i,r)
    }  
    return(mat)
}), itemnames)

# OUTPUT INDIVIDUAL ELEMENTS TO SEPARATE GLOBAL OBJECTS
list2env(matlist, envir=.GlobalEnv)
Parfait
  • 104,375
  • 17
  • 94
  • 125