[R] Variable names AS variable names?

Jonathan P Daily jdaily at usgs.gov
Fri Feb 25 19:09:28 CET 2011


To access a variable by a character string name, try

for(code in codes)
{
dat <- get(code)
[stuff]
}

Other options include ?assign if you need to manipulate the original, or 
?with to use the subject of "codes" as an environment.
--------------------------------------
Jonathan P. Daily
Technician - USGS Leetown Science Center
11649 Leetown Road
Kearneysville WV, 25430
(304) 724-4480
"Is the room still a room when its empty? Does the room,
 the thing itself have purpose? Or do we, what's the word... imbue it."
     - Jubal Early, Firefly

r-help-bounces at r-project.org wrote on 02/25/2011 12:33:32 PM:

> [image removed] 
> 
> Re: [R] Variable names AS variable names?
> 
> Noah Silverman 
> 
> to:
> 
> 02/25/2011 12:35 PM
> 
> Sent by:
> 
> r-help-bounces at r-project.org
> 
> Cc:
> 
> r-help
> 
> My actual code is several things with adaptive filtering.  This will
> require accessing data sporadically.  The loop was just a quick example
> for the e-mail.
> 
> One application is to work with online (streaming) data.  If I get a new
> data point in for code "a1", I'll need to be able to reference the
> matrix named "a1". 
> 
> On 2/25/11 12:23 AM, David Winsemius wrote:
> >
> > On Feb 25, 2011, at 1:55 AM, Noah Silverman wrote:
> >
> >> How can I dynamically use a variable as the name for another 
variable?
> >>
> >> I realize this sounds cryptic, so an example is best:
> >>
> >> #Start with an array of "codes"
> >> codes <- c("a1", "b24", "q99")
> >
> > Is there some reason not to use list(a1, b24, q99)? If not then:
> >
> > lapply(codes, somefun)
> >
> >
> >>
> >> #Each code has a corresponding matrix (could be vector)
> >> a1 <- matrix(rnorm(100), nrow=10)
> >> b24 <- matrix(rnorm(100), nrow=10)
> >> q99 <- matrix(rnorm(100), nrow=10)
> >>
> >> #Now, I want to loop through all the codes and do something with each
> >> matrix
> >> for(code in codes){
> >>    #here is where I'm stuck.  I don't want the value of code, but the
> >> variable who's name is the value of code
> >>
> >> }
> >>
> >>
> >> Any suggestions?
> >>
> >> -N
> >>
> >> ______________________________________________
> >> 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
> >
> 
> ______________________________________________
> 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.



More information about the R-help mailing list