[R] Substring replacement in string

William Dunlap wdunlap at tibco.com
Fri Feb 27 23:39:21 CET 2015


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