0

Possible Duplicate:
generate variable names (something like get())

If I want to create matrices with different names in an automatized way, I run into problems.

For example, I want to create three matrices named a1,a2 and a3.

 x<-1:3
 a<-"a"
 listofnames<-paste(a,x)  ## a vector with the names that I want to use for my matrices

My problem is to assign a matrix the different names from the vector I created. For example, to create a matrix called a1 (the first "name" in my vector), this will of course not work at all:

 listofnames[1]<-matrix(ncol=2,nrow=2)

But how would I do it?

I've been looking on the internet but can't find any answer.. Thank you so much for your help

Community
  • 1
  • 1

2 Answers2

3

Use assign as in:

x<-1:3
a<-"a"
listofnames <-paste(a,x) 

set.seed(001)
for(i in 1:length(listofnames)){
  assign(listofnames[i], matrix(sample(9), ncol=3))
}


get(listofnames[1])
     [,1] [,2] [,3]
[1,]    3    6    8
[2,]    9    2    7
[3,]    5    4    1

get(listofnames[2])
     [,1] [,2] [,3]
[1,]    1    5    6
[2,]    2    7    3
[3,]    8    4    9

get(listofnames[3])
     [,1] [,2] [,3]
[1,]    4    2    5
[2,]    7    9    3
[3,]    8    1    6

Once you assign matrices to the names contained in listofnames you can access by using get function as shown above. If you only do listofnames[1] this will give you the firt name in listofnames but not the elements stored under that name, to do so you must use get(listofnames[1])

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
  • You don't actually need to use `get`, but since the names are not standard (`a 1` -- with a space), you need to use `\`a 1\`` to return the output. – A5C1D2H2I1M1N2O1R2T1 Oct 30 '12 at 16:34
  • @mrdwab you're right. I meant the OP needs to use `get` when calling the matrices this way: `listofnames[1]`, this will only gives him/her the first name contained in `listofnames`, if he/she wants the data stored in the first name which is in `listofnames` he/she will need to use `get` as in `get(listofnames[1])`, but if the OP types directly the name as in your comment, then `get` will not be needed. – Jilber Urbina Oct 30 '12 at 16:49
  • Aah. Got it. +1 for the complete example. – A5C1D2H2I1M1N2O1R2T1 Oct 30 '12 at 17:01
  • Although this answers the question of the OP, I would still like stress that I feel using `assign` is suboptimal. Using a list is much more convient, e.g. in combination with `apply` style loops. See e.g. http://stackoverflow.com/questions/5319839/read-multiple-csv-files-into-separate-data-frames/5320643#5320643. – Paul Hiemstra Oct 30 '12 at 22:35
1

It might be better if you explain exactly what you are trying to achieve, but you might also want to explore assign():

x <- 1:3
a <- "a"
listofnames <- paste(a, x, sep="")
assign(listofnames[1], matrix(nrow = 2, ncol = 2))
a1
     [,1] [,2]
[1,]   NA   NA
[2,]   NA   NA
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485