Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match several substitution patterns with a single expression

Tags:

string

regex

r

gsub

I know from the R documentation that the gsub function can be programmed to do simultaneous operations like upper/lowercase substitution:

gsub("([a-z]*)([A-Z]*)", "\\U\\1\\L\\2", "upper LOWER", perl=TRUE)

[1] "UPPER lower"

I have a minimal example, a string "STTS", in which I want to replace "S" with "TRUE" and "T" with "FALSE". I cannot do it sequentially because the matching patterns would obviously collide.

I have tried this code:

gsub("([S]*)\\1([T]*)\\2", "TRUE \\1FALSE \\2", "STTS",perl=TRUE)

and received [1] "TRUE FALSE STRUE FALSE TSTRUE FALSE "

instead of "TRUE FALSE FALSE TRUE"

like image 908
user24504409 Avatar asked Oct 15 '25 00:10

user24504409


1 Answers

The mgsub package allows for simultaneous substitution:

library(mgsub)

mgsub("STTS", c("S", "T"), c("TRUE ", "FALSE "))
[1] "TRUE FALSE FALSE TRUE "
like image 127
LMc Avatar answered Oct 17 '25 14:10

LMc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!