Skip to content
Back to formatted view

Raw Message

Message-ID: <4DD6F8B8782D584FABF50BF3A32B03D801A2BBC0@MSGBOSCLF2WIN.DMN1.FMR.COM>
Date: 2005-05-11T22:41:18Z
From: Brahm, David
Subject: string syntactic sugar in R? - long post

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)