[R] Interpolating variables into quoted strings

David Brahm brahm at alum.mit.edu
Mon Sep 16 18:03:15 CEST 2002


William M. Fitchen <William_Fitchen at oxy.com> wrote on 12/19/01:

> I am new to R and am coming from a Perl background. I have had trouble 
> figuring out from the documentation how to interpolate a variable into a 
> quoted string (if it's possible).... In perl I could write: 
>        $name = "John"; 
>        print STDOUT "Hi $name, how's it going"; 
> which would output the following: 
>        Hi John, how's it going? 

I just wrote such a function; here is its current form:

g.p <- function(..., esc="\\$", sep="", collapse=" ") {
  a <- lapply(list(...), as.character)
  n <- names(a);  if (is.null(n)) n <- rep("", length(a))
  s <- do.call("paste", c(a[n==""], sep=sep, collapse=collapse))
  for (i in which(n != "")) s <- gsub(paste(esc,n[i],sep=""), a[[i]], s)
  while ((r <- regexpr(paste(esc,"\\w*",sep=""), s)) > 0) {
    v <- substring(s, r+1, r+attr(r,"match.length")-1)
    s <- gsub(paste(esc,v,sep=""), as.character(eval(parse(text=v))), s)
  }
  s
}

It does three things:
1) Concatenates all unnamed arguments (with sep="" by default);
2) Uses any named arguments such as var1=7 to interpolate $var1 in the string;
3) Interpolates any remaining $var2 constructions using all visible variables.

Note I didn't allow "." in variable names, for consistency with Perl.

William's example can be accomplished with either:
 R> g.p("Hi $name, how's it going",  name="John")
or:
 R> name <- "John"
 R> g.p("Hi $name, how's it going")

Comments welcome!
-- 
                              -- David Brahm (brahm at alum.mit.edu)
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list