Hi,
I'm a long-time STATA user and a R newbie. I'm doing ok, but I'm
addicted
to STATA macro variables. Is there something like a macro variable in R?
Specifically, I'd like to be able to do something like
for (i in 1:3) {
.....
x`i' <- ...
}
where R would resolve x`i' to the objects named x1, x2 and x3 as I move
through the loop. I guess I could create these in advance of the loop and
fill them in, but I'd rather not.
Is there a way to use an index of a loop in this manner?
thanks,
michael
E. Michael Foster
Professor of Maternal and Child Health
School of Public Health
University of North Carolina
x <- rep(NA, 3)
for (i in 1:length(x)){
x[i] <- ...
}
will do the job, but you may be able to take advantage of R's vectorization
and do what you want with no loop at all.
Charles Annis, P.E.
Charles.Annis at StatisticalEngineering.com
phone: 561-352-9699
eFax: 614-455-3265
http://www.StatisticalEngineering.com
-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of E. Michael Foster
Sent: Monday, July 04, 2005 4:32 PM
To: r-help at stat.math.ethz.ch
Subject: [R] using index of a loop as a macro variable
Hi,
I'm a long-time STATA user and a R newbie. I'm doing ok, but I'm
addicted
to STATA macro variables. Is there something like a macro variable in R?
Specifically, I'd like to be able to do something like
for (i in 1:3) {
.....
x`i' <- ...
}
where R would resolve x`i' to the objects named x1, x2 and x3 as I move
through the loop. I guess I could create these in advance of the loop and
fill them in, but I'd rather not.
Is there a way to use an index of a loop in this manner?
thanks,
michael
E. Michael Foster
Professor of Maternal and Child Health
School of Public Health
University of North Carolina
______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html
On Mon, 4 Jul 2005, E. Michael Foster wrote:> I'm a long-time STATA user and a R newbie. I'm doing ok, but I'm addicted > to STATA macro variables. Is there something like a macro variable in R? > > Specifically, I'd like to be able to do something like > > for (i in 1:3) { > ..... > x`i' <- ... > } > > where R would resolve x`i' to the objects named x1, x2 and x3 as I move > through the loop. I guess I could create these in advance of the loop and > fill them in, but I'd rather not. > > Is there a way to use an index of a loop in this manner?No. Well, actually, yes, but you don't want to. Stata macros rarely translate word-for-word into R. There is a FAQ describing how to do this sort of thing, but the most important paragraph is the last one, where it says not to do this. What you want is a list. for(i in 1:3){ ..... x[[i]]<-... } Now, x needs to exist before the loop. You can use x<-NULL to create it, or if you know how long it will be you can use x<-vector("list",3) -thomas