RE: [R] Search and convert string function

From: Brahm, David <David.Brahm_at_geodecapital.com>
Date: Tue 08 Mar 2005 - 07:25:47 EST


peng shen [mailto:michael_shen@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:

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
}
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 Tue Mar 08 07:30:25 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:30:41 EST