Skip to content

Reference variables by string in for loop

5 messages · Michael Bach, Kenn Konstabel, Nick Sabbe

#
Dear R Users,

I am trying to get the following to work better:

namevec <- c("one", "two", "three")
for (name in namevec) {
    namedf <- eval(parse(text=paste(name, "_df", sep="")))
    ...
    ...
}

The rationale behind it being that I created variables with names
one_df, two_df and three_df earlier in the same script which I want to
reference inside the for loop.  Is there a more elegant way to do this?

Best Regards,
Michael Bach
#
On Fri, Apr 29, 2011 at 1:03 PM, Michael Bach <phaebz at gmail.com> wrote:
Yes, one elegant way to do it would be using a named list instead of
separate variables.

X <- list()
X$one_df <- "something"
X[["two_df"]] <- "something else"
NAME <- "one_df"
X[[NAME]]
NAME <- "two_df"
X[[NAME]]
#etc

# the for loop could then be: for(name in names(X)) ... or for(element in X)

Another way (not elegant but better and shorter than the eval-parse
way) is to use get. ?get

Best regards,

Kenn
#
Hi Michael.
This is a classic :-)

ObjectsOfInterest<- list(one_df, two_df, three_df)
for(namedf in ObjectsOfInterest){...}

or probably even better
sapply(ObjectsOfInterest, function(namedf){...})

hth.


Nick Sabbe
--
ping: nick.sabbe at ugent.be
link: http://biomath.ugent.be
wink: A1.056, Coupure Links 653, 9000 Gent
ring: 09/264.59.36

-- Do Not Disapprove




-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Michael Bach
Sent: vrijdag 29 april 2011 12:03
To: r-help at r-project.org
Subject: [R] Reference variables by string in for loop

Dear R Users,

I am trying to get the following to work better:

namevec <- c("one", "two", "three")
for (name in namevec) {
    namedf <- eval(parse(text=paste(name, "_df", sep="")))
    ...
    ...
}

The rationale behind it being that I created variables with names
one_df, two_df and three_df earlier in the same script which I want to
reference inside the for loop.  Is there a more elegant way to do this?

Best Regards,
Michael Bach

______________________________________________
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.
#
"Nick Sabbe" <nick.sabbe at ugent.be> writes:
I see. This is also more readable and traceable for others.
I like this one for its functional style.
It did, thanks.

Kind Regards,
Michael Bach
#
Kenn Konstabel <lebatsnok at gmail.com> writes:
This one is handy for interactive use, thanks for the hint.

Kind Regards,
Michael Bach