[R] Substring replacement in string
Alrik Thiem
alrik.thiem at gmail.com
Sat Feb 28 08:25:31 CET 2015
Many thanks. Unfortunately, I cannot work directly on these expressions since they’re only created from other strings. Would I first have to transform these strings to unevaluated expressions?
Von: William Dunlap [mailto:wdunlap at tibco.com]
Gesendet: Freitag, 27. Februar 2015 23:39
An: Alrik Thiem
Cc: r-help at r-project.org
Betreff: Re: [R] Substring replacement in string
If your string will always represent an R expression, you could work with
the expression directly with functions like all.names() and substitute().
f <- function (expr)
{
toReplace <- setdiff(all.names(expr), c("pmin", "pmax"))
toReplace <- grep(value = TRUE, "[a-z]", toReplace)
names(toReplace) <- toReplace
replacementList <- lapply(toReplace, function(name) call("-",
1, as.name(toupper(name))))
do.call(substitute, list(expr, replacementList))
}
> In <- quote(pmin(pmax(pmin(x1, X2), pmin(X3, X4)) == Y, pmax(Z1, z1)))
> Desired <- quote(pmin(pmax(pmin(1 - X1, X2), pmin(X3, X4)) == Y, pmax(Z1, 1 - Z1)))
> all.equal(Desired, f(In))
[1] TRUE
Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Fri, Feb 27, 2015 at 2:19 PM, Alrik Thiem <alrik.thiem at gmail.com> wrote:
Dear R-help list,
I would like to replace all lower-case letters in a string that are not part
of certain fixed expressions. For example, I have the string:
"pmin(pmax(pmin(x1, X2), pmin(X3, X4)) == Y, pmax(Z1, z1))"
Where I would like to replace all lower-case letters that do not belong to
the functions "pmin" and "pmax" by 1 - toupper(...) to get
"pmin(pmax(pmin(1 - X1, X2), pmin(X3, X4)) == Y, pmax(Z1, 1 - Z1))"
Any ideas on how I could achieve that?
Many thanks and best wishes,
Alrik
********************************
Alrik Thiem
Post-Doctoral Researcher
Department of Philosophy
University of Geneva
Rue de Candolle 2
CH-1211 Geneva
+41 76 527 80 83
http://www.alrik-thiem.net
http://www.compasss.org
______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.
[[alternative HTML version deleted]]
More information about the R-help
mailing list