Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

replaceText

Replace text in a string


Description

Provides an improved method to replace strings, compared to function gsub() in package base.

Usage

replaceText(expression = "", target = "", replacement = "", boolean = FALSE, ...)

Arguments

expression

Character string, usually a SOP - sum of products expression.

target

Character vector or a string containing the text to be replaced.

replacement

Character vector or a string containing the text to replace with.

boolean

Treat characters in a boolean way, using upper and lower case letters.

...

Other arguments, from and to other functions.

Details

If the input expression is "J*JSR", and the task is to replace "J" with "A" and "JSR" with "B", function gsub() is not very useful since the letter "J" is found in multiple places, including the second target.

This function finds the exact location(s) of each target in the input string, starting with those having the largest number of characters, making sure the locations are unique. For instance, the target "JSR" is found on the location from 3 to 5, while the target "J" is is found on two locations 1 and 3, but 3 was already identified in the previously found location for the larger target.

In addition, this function can also deal with target strings containing spaces.

Value

The original string, replacing the target text with its replacement.

Author(s)

Adrian Dusa

Examples

replaceText("J*JSR", "J, JSR", "A, B")

# same output, on input expresions containing spaces
replaceText("J*JS R", "J, JS R", "A, B")

# works even with Boolean expressions, where lower case
# letters signal the absence of the causal condition
replaceText("DEV + urb*LIT", "DEV, URB, LIT", "A, B, C", boolean = TRUE)

admisc

Adrian Dusa's Miscellaneous

v0.12
GPL (>= 3)
Authors
Adrian Dusa [aut, cre, cph] (<https://orcid.org/0000-0002-3525-9253>)
Initial release
2021-03-16

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.