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 Michael
Search and convert string function
3 messages · peng shen, Gabor Grothendieck, Brian Ripley
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"
On Sun, 6 Mar 2005, peng shen wrote:
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
sub("$R", R, testString, fixed = TRUE)
Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595