I want to replace:
(1) ", "
(comma+space) with "_"
(underscore)
(2) "'"
(apostrophe) with "'s"
(apostrophe+s)
library(gsubfn)
x <- c("Mary' car is red.", "A, B, C")
gsubfn(".", list(", " = "_", "'" = "'s"), x)
what I want is "Mary's car is red."
and "A_B_C"
, but the result is "Mary's car is red."
and "A, B, C"
. Why?
Try this:
toreplace<-list(", " = "_", "'" = "'s")
gsubfn(paste(names(toreplace),collapse="|"),toreplace,x)
#[1] "Mary's car is red." "A_B_C"
The problem with your approach is that your pattern was just a single character (.
) and couldn't match ", "
.
x <- c("Mary' car is red.", "A, B, C")
l <- list(r1 = c("'","'s"),
r2 = c(', ','_'))
gsub2 <- function(l, x, ...)
do.call('gsub', c(list(x = x, pattern = l[1], replacement = l[2]), ...))
Reduce('gsub2', l, x, right = TRUE)
# [1] "Mary's car is red." "A_B_C"
Or more
l <- list(r1 = c("'","'s"),
r2 = c(', ','_'),
r3 = c('M', 'Mmmm'),
r4 = c('\\br', 'rrrr'),
r5 = c('\\.', '!!!'))
Reduce('gsub2', l, x, right = TRUE)
# [1] "Mmmmary's car is rrrred!!!" "A_B_C"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With