[R] macro variable in R?

Peter Dalgaard pdalgd at gmail.com
Fri Apr 23 23:07:07 CEST 2010


karena 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?

First, the standard counterquestion is "Why?". What do you gain over

ml <- lapply(1:10,function(i)matrix(,i,i))
ml[[1]]
..
ml[[10]]

??

If you insist on cluttering up your workspace with 10 separate
variables, it can be done with

for (i in 1:10)
   assign(paste("matrix",i,sep="_"), matrix(,i,i))

(There are situations where you do wish for macro-like substitutions in
R, I just don't think this is one of them. One case is when you perform
similar analyses for different responses, as in

for (i in list(diabt, sysbt, chol))
  print(summary(lm(i~age+sex)))

and all three regression analysis come out with response variable "i"
rather than the relevant variable name. This too is doable with some
eval(bquote(...)) trickery.)

-- 
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list