[R] macro function

Joshua Wiley jwiley.psych at gmail.com
Tue Feb 28 10:20:05 CET 2012


Hi,

There is not anything really like macro functions in R (and honestly,
that is probably a good thing).  Most the times I have seen people
generating thousands of variables (vectors in your case) it is due to
a lack of understanding how lists can be utilized to simplify code.
If you give us some context on what all these vectors will be used
for, we may be able to suggest an easier way to accomplish your goals.

If you must create vectors:

sapply(1:3003, function(i) {
  assign(paste("r", i, sep = ''), rnorm(1), envir = .GlobalEnv)
})

or with a for loop:

for (i in 1:3003) {
  assign(paste("r", i, sep = ''), rnorm(1), envir = .GlobalEnv)
}

HTH,

Josh

On Tue, Feb 28, 2012 at 12:14 AM, mrzung <mrzung46 at gmail.com> wrote:
> hi,
>
> I know how to use the "for" loop function like:
>
> for(i in 1:ncol(mat)){
> mat[i]<-b[i,2]
> }
>
> but, in this case
>
> r1<-b[1,1]
> r2<-b[2,1]
> r3<-b[3,1]
> r4<-b[4,1]
>
> *
> *
> *
>
> r3002<-b[3002,1]
> r3003<-b[3003,1]
>
> - must make vectors
>
> how should I make a efficient code for that?
>
> Is there anything in R like SAS MACRO function?
>
> --
> View this message in context: http://r.789695.n4.nabble.com/macro-function-tp4427385p4427385.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list