Re: [R] replace an expression with its value, or read macros

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Thu, 07 Apr 2011 20:19:41 -0400

On Thu, Apr 7, 2011 at 7:45 PM, Franklin Tamborello II <Franklin.Tamborello_at_uth.tmc.edu> wrote:
> I know my subject line seems odd, but I want to replace an expression—such as a variable—with its value. For example, I want to paste() some strings together, assign the result to a variable s, then use the value of s as a variable to hold another value. Something like this:
>
> import_subjects <- function (start, iterations) {
> for (i in 1:iterations) { # iterate from start to end
> s <- paste("s", i, sep="") # make the data.frame's name
> fn <- paste(i, ".txt", sep="") # make the filename
> s <- read.delim(fn, header = FALSE) # now put it all together
> # …except that I don't want to reassign s, I want to evaluate it and make its value a variable with its own value.
> }
> }
>
> If this were Lisp I'd use backquotes (or "backticks", as some say) and commas—examples of read macros—to do this, but I can't find anything analogous for R. How might I accomplish this in R?
>

Here are a few possibilities:

# 1 - assign
assign(s, read.delim(fn, header = FALSE)

# 2 - .GlobalEnv
.GlobalEnv[[s]] <- read.delim(fn, header = FALSE)

# 3 - gsubfn's fn$ supports backticks
# Here we need gsubfn::fn to disambiguate the two fn's library(gsubfn)
eval(gsubfn::fn$parse(text = " `s` <- read.delim(fn, header = FALSE) "))

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

______________________________________________
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 08 Apr 2011 - 00:23:40 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 08 Apr 2011 - 00:30:28 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