Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple string replacement, using gsubfn() in R

Tags:

string

r

gsub

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?

like image 866
Eric Chang Avatar asked Dec 24 '22 11:12

Eric Chang


2 Answers

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 ", ".

like image 130
nicola Avatar answered Jan 09 '23 22:01

nicola


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"
like image 42
rawr Avatar answered Jan 09 '23 23:01

rawr