0

I have the following problem: I have a huge list of matrices with unique names that share the same dimension. I calculate some values that I now want to assign to a certain matrix indice, e.g. [3,4]. Because I have so many matrices I created a list with the names that those matrices shall have and then I used assign() to create all those matrices (empty). I would now like to call single matrices with its variable name to assign different values to certain matrix entries. I only know the commands assign() and eval(parse()), but didn't manage to get it working. I tried several things without success:

assign(x=MatrixNameList[i][3,4],value=z)

assign(x=MatrixNameList[i],value=z)[3,4]

eval(parse(text=MatrixNameList[i]))[3,4]<-z

assign(x=eval(parse(text=MatrixNameList[i]))[3,4] ,value=z)

So I am wondering if there is a possibility for what I want to do. The structure of my code is a simple loop:

Matrix1 <- Matrix2 <- matrix(nrow=3,ncol=4)
MatrixNameList <- c('Matrix1', 'Matrix2')
for (i in 1:length(MatrixNameList)){
z <- calculatedValue <- 4 # different for the single matrices
assign... ?
eval(parse... ?
}

I hope I was able to clearly point out my problem. Thanks in advance, Eric

Eric
  • 137
  • 2
  • 8
  • 2
    If you went to the trouble to put the names of your matrices in a list, you should just put the matrices themselves in a list (which you really should have done in the first place). Then your task would be trivial. – joran Jun 12 '13 at 13:49
  • 1
    You don't have a huge list of matrices. If you had a huge list of matrices, `lapply(matlist, function(m) {m[3,4] <- z; m})` would be the solution. – Joshua Ulrich Jun 12 '13 at 13:50
  • @joran: I create the matrix names with paste(); I assumed that once the object gets very big (assume matrix of 10000*10000), it would be better to have many separate ones instead of one that is xxx times the size of the already big one. But I guess it doesn't matter. Thanks for reply. – Eric Jun 13 '13 at 10:05
  • @JoshuaUlrich: matlist is the list object, but is there a way with get() or assign() to 'call' the variable from a list with strings? Just curious. Thanks for the reply. – Eric Jun 13 '13 at 10:09

2 Answers2

1

Use get:

get(MatrixNameList[1])  # retrieves matrix called "Matrix1"

However, you're better off collecting all those matrices into one object. Something like this should get you started.

Matrices <- lapply(MatrixNameList, get)
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
1

You can assign values like the following:

MatrixList <- list(Matrix1, Matrix2)
names(MatrixList) <- MatrixNameList

MatrixList[[1]][2,3] <- 4
# OR:
MatrixList$Matrix1[2,3] <- 4
Thomas
  • 43,637
  • 12
  • 109
  • 140