[R] string syntactic sugar in R? - long post

Brahm, David David.Brahm at geodecapital.com
Thu May 12 00:41:18 CEST 2005


charles loboz <charles_loboz at yahoo.com> wrote:
> A gstring is a string with variable names embedded and replaced by
> values(converted to strings, lazy eval) before use.

I use the following function, which will take variables either from
named arguments or from the environment.  It also concatenates all
unnamed arguments (with sep="") as a convenience for long strings.

g.p <- function(..., esc="\\$", sep="", collapse=" ", parent=1) {
  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 <- if (v=="") paste(substring(s,1,r-1), substring(s,r+2), sep="")
         else gsub(paste(esc,v,sep=""),
              as.character(eval.parent(parse(text=v), parent)), s)
  }
  s
}

Here's a simple example:

R> alpha <- 8
R> g.p("the result is $alpha with the comment $beta",
       beta="xyz")
   [1] "the result is 8 with the comment xyz"

-- David Brahm (brahm at alum.mit.edu)




More information about the R-help mailing list