Skip to content
Back to formatted view

Raw Message

Message-ID: <4DD6F8B8782D584FABF50BF3A32B03D801A2BB6D@MSGBOSCLF2WIN.DMN1.FMR.COM>
Date: 2005-03-07T20:25:47Z
From: Brahm, David
Subject: Search and convert string function

peng shen [mailto:michael_shen at hotmail.com] wrote:
> R <- 4
> testString <- "I love $R"
> So the final string I want to get is "I love 4".  How can I implement?

I've written an interpolater function "g.p" with these additional
features:
 - Loops through all occurences of the escape character ($) rather than
all
   external variables.
 - Variable names are terminated by any non-alphanumeric char or a
"silent" $$.
 - Variables may come from the parent environment or from named
arguments.
 - Pastes together its unnamed arguments with sep="", useful for long
strings.

Example:
R> R <- 4
R> testString <- "I love $R"
R> g.p(testString)
   [1] "I love 4"

Fancier example:
R> var1 <- 7
R> var2 <- 5
R> g.p("Add $var1 to $var2 to calc",
       "ulate $var3",
       var3=var1+var2)
   [1] "Add 7 to 5 to calculate 12"

Function definition:
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
}

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