-1

I want to redefine propperly elements of a multidimensional matrix using assign on R.

I tried this

lat = 3
lon = 3
laidx = 1:3
loidx = 1:3
OtherDF is a 3x3 multidimensional matrix, and each element is a large data frame

for (i in 1:12){

  assign(paste("STAT",i,sep=""),array(list(NA), dim=c(length(lat),length(lon))))

  for (lo in loidx){
    for (la in laidx){

    assign(paste("STAT",i,"[",la,",",lo,"]",sep=""), as.data.frame(do.call(rbind,otherDF[la,lo])))
    # otherDF[la,lo] are data frames


    } 
  }
}

First I created 12 empty matrix STATS1,STATS2 ,...,STATS12 (I need 12, one for each month)

Then I tried to fill them with elements of an other dataframe, but instead of filling it create a lot of new variables like this `STAT10[[1,1]]``

Some help please

Forever
  • 385
  • 3
  • 16
  • 1
    The first assign statement is fine. Once you have that by calling `assign(paste("STAT",i,"[",la,",",lo,"]",sep=""),...)` you are creating a new variable and you are not accessing the one you already created. – A Gore Jul 17 '17 at 13:11
  • But how can i access the one I already created ? Thanks @AGore – Forever Jul 17 '17 at 13:15
  • https://stats.stackexchange.com/questions/10838/produce-a-list-of-variable-name-in-a-for-loop-then-assign-values-to-them – A Gore Jul 17 '17 at 13:22
  • 1
    Generally using `assign` is frowned upon; there are usually better alternatives to solving problems in R. Plus `assign` only works with variable names `x[i]` is not a variable name, it's actually calling the function `[` with `x` and `i` as parameters. Anyway, it would be better to include a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data and the desired output so that a better strategy can be suggested. – MrFlick Jul 17 '17 at 14:17

1 Answers1

1

Since you don't provide your data, I made up some:

lat = 3
lon = 3
otherDF <- data.frame(A=1:3, B=4:6, C=7:9)
loidx <- 1:3
laidx <- 1:3

I avoid the nested for loops and the second assign statement with expand.grid and sapply(iter(idx,by="row", function(x) otherDF[x$Var1,x$Var2]).

install.packages("iterators")
for (i in 1:12){
    library(iterators)
    idx <- expand.grid(loidx,laidx)    # expands all combinations of elements in loidx and laidx
    assign(paste0("STAT",i), matrix(sapply(iter(idx, by="row"), function(x) otherDF[x$Var1, x$Var2]), ncol=3))
}

I made some guesses on what you wanted based on your code, so edit your original post if you wanted something different.

CPak
  • 13,260
  • 3
  • 30
  • 48