Re: [R] Reference variables by string in for loop

From: Kenn Konstabel <lebatsnok_at_gmail.com>
Date: Fri, 29 Apr 2011 14:01:00 +0300

On Fri, Apr 29, 2011 at 1:03 PM, Michael Bach <phaebz_at_gmail.com> wrote:
> 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?

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



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. Received on Fri 29 Apr 2011 - 11:04:36 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 29 Apr 2011 - 12:50:35 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive