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")
#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
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
One of my hypotheses of what you want is:
for(code in codes) {
get(code)
}
The other one is:
for(code in codes) {
as.name(code)
}
On 25/02/2011 06:55, 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")
>
> #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.
>
--
Patrick Burns
pburns at pburns.seanet.com
twitter: @portfolioprobe
http://www.portfolioprobe.com/blog
http://www.burns-stat.com
(home of 'Some hints for the R beginner'
and 'The R Inferno')