Re: [R] Search and convert string function

From: Gabor Grothendieck <ggrothendieck_at_myway.com>
Date: Sun 06 Mar 2005 - 14:04:38 EST

peng shen <michael_shen <at> hotmail.com> writes:

:
: Hi all,
: I want to do this kind of function In R enviroment :
: For example :
: R <- 4
: testString <- "I love $R"
: then search this testString, when find "$R",replace "$R" to R ,and because
: the value of R is 4
: So the final string I want to get is "I love 4"
: How can I implement? Thanks advance
:

Here is one way to do string interpolation:

R> interp <- function(x, e = parent.frame(), pre = "\\$", post = "" ) {

+    for(el in ls(e)) {
+       tag <- paste(pre, el, post, sep = "")
+       if (length(grep(tag, x))) x <- gsub(tag, eval(parse(text = el), e), x)
+    }
+    x
+ }
 
R> # a test
R> R <- 4

R> x <- "I love $R"
R> interp(x)
[1] "I love 4"  
R> # another test
R> y <- "I love ${R}"
R> interp(y, pre = "\\${", post = "}")

[1] "I love 4"

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 Sun Mar 06 14:17:35 2005

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