Bill Dunlap TIBCO Software Inc - Spotfire Division wdunlap tibco.com
> -----Original Message----- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of Wacek Kusnierczyk > Sent: Thursday, May 28, 2009 12:31 PM > To: Caroline Bazzoli > Cc: r-help@r-project.org > Subject: Re: [R] String replacement in an expression > > Caroline Bazzoli wrote: > > Dear R-experts, > > > > I need to replace in an expression the character "Cl" by "Cl+beta" > > > > But in the following case: > > > > form<-expression((Cl-(V *ka) ) +(V *Vm *exp(-(Clm/Vm) *t))) > > > > gsub("Cl","(Cl+beta)",as.character(form)) > > > > We obtain: > > > > [1] "((Cl+beta) - (V * ka)) + (V * Vm * exp(-((Cl+beta)m/Vm) * t))" > > > > > > the character "Clm" has been also replaced. > > > > > > How could I avoid this unwanted replacement ? > > try '\\bCl\\b' as the pattern, which says 'match Cl as a > separate word'. That works in this case, but \\b idea of what a word is not same as R's idea of what a name is. E..g, \\b thinks that a period is not in a word but R thinks periods in names are fine. > gsub("\\bC1\\b", "(C1+beta)", "C1 * exp(C1.5 / C2.5)") [1] "(C1+beta) * exp((C1+beta).5 / C2.5)" This is one more reason to use substitute(), which directly edits an expression to produce a new one. It avoids the deparse-edit-parse cycle that can corrupt things (even if you don't do any editing). > substitute(C1 * exp(C1.5 / C2.5), list(C1=Quote(C1+beta))) (C1 + beta) * exp(C1.5/C2.5) Bill Dunlap TIBCO Software Inc - Spotfire Division wdunlap tibco.com > > > vQ > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.