[R] macro variable in R?

Steve Lianoglou mailinglist.honeypot at gmail.com
Thu Apr 22 18:24:44 CEST 2010


Hi,

On Thu, Apr 22, 2010 at 12:08 PM, karena <dr.jzhou at gmail.com> wrote:
>
> I need to create 10 matrices. say matrix 1-10.
>
> matrix_1 is 1 by 1
> matrix_2 is 2 by 2
> matrix_3 is 3 by 3
>   .
>   .
>   .
> matrix_10 is 10 by 10
>
> I am just wondering if there are some functions in R that are similar to the
> macro variables in SAS. so I can create these 10 matrices by doing:
> for (i in 1: 10) {
> matrix_$i <- matrix(nrow=i, ncol=i)
> }
>
> rather thank creating these matrices one by one manually.
>
> Anyone have any suggestions?

I believe the most idiomatic R way is to make a list of length 10:

R> mats <- lapply(1:10, function(x) matrix(0, nrow=x, ncol=x))

Then reference them like so:

R> mats[[1]]

If you *really* want them to be in your global namespace, you have two options:

1. You can slightly modify the `mat` list I made above with more
"variable-friendly" names and then `attach` it (or use `with`):

R> names(mats) <- paste("m", 1:10, sep="")
R> attach(mats)
R> m2
     [,1] [,2]
[1,]    0    0
[2,]    0    0

2. Or you could forget the `lapply` from above use `assign` in a for loop:

R> for (i in 1:10) {
  assign(sprintf('mat%d', i), matrix(0, nrow=i, ncol=i))
}
R> mat2
     [,1] [,2]
[1,]    0    0
[2,]    0    0

Other notes: using "attach" isn't really best practice -- look into using `with`

Documentation you should read:

?lapply
?attach
?with
?assign

-steve

-- 
Steve Lianoglou
Graduate Student: Computational Systems Biology
 | Memorial Sloan-Kettering Cancer Center
 | Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact



More information about the R-help mailing list