[R] macro variable in R?

David Winsemius dwinsemius at comcast.net
Thu Apr 22 19:25:00 CEST 2010


On Apr 22, 2010, at 12:24 PM, Steve Lianoglou wrote:

> 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))

A somewhat similar method using Map:

  mtxlist <- Map(matrix, rep(0,10), 1:10, 1:10)
  names(mtxlist) <- paste("matrix", 1:10, sep="_")
  mtxlist$matrix_1
  mtxlist$matrix_10

Or with nested Map/mapply calls:

  mtxlist <- Map(assign, paste("matx", 1:10, sep="_"), Map(matrix,  
rep(0,10), 1:10, 1:10) )

And if you wanted to have all of those individual mtx_<n>'s floating  
around:

  mapply(assign,
            paste("matx", 1:4, sep="_"),
            Map(matrix, 1:4, 1:4, 1:4),
            MoreArgs=list( envir=.GlobalEnv) )


>
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list