[R] Search and convert string function
Gabor Grothendieck
ggrothendieck at myway.com
Sun Mar 6 04:04:38 CET 2005
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"
More information about the R-help
mailing list