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

From: Brahm, David <David.Brahm_at_geodecapital.com>
Date: Thu 12 May 2005 - 08:41:18 EST


charles loboz <charles_loboz@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"


R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Thu May 12 16:33:44 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:42 EST