Rajan
Rajan

Reputation: 463

Replace special characters with other special character in R

I want to remove some special characters to some other special characters. Here are two vectors.

a <- c('%', '&')
b <- c('\%', '\&')

I want to replace elements of vector a to corresponding elements of vector b from vector v1.

v1 <- c('I got 95% in maths & 80% in science',
        'He got 90% in maths & 70% in science')

I tried gsub but it did't work. Also I am not able to create vector b as it gave following error.

Error: '\%' is an unrecognized escape in character string starting "'\%"

Upvotes: 1

Views: 1578

Answers (3)

Ken Benoit
Ken Benoit

Reputation: 14902

The error is generated by the \ in your object b not being escaped. Try it as below and it will work. Note that the string itself displays as a single backslash using cat() but prints with the two. To define a \ in an R character object, you need to escape it.

Note that to do the vectorised replacement of each element in a for each in b, I used stringi, which is well suited to vectorised replacements.

a <- c('%', '&')
b <- c('\\%', '\\&')
c <- c("I got 95% in maths & 80% in science", "He got 90% in maths & 70% in science")

(result <- sapply(c, stringi::stri_replace_all_fixed, a, b, vectorize_all = FALSE, USE.NAMES = FALSE))
## [1] "I got 95\\% in maths \\& 80\\% in science"  "He got 90\\% in maths \\& 70\\% in science"

cat(result)
## I got 95\% in maths \& 80\% in science He got 90\% in maths \& 70\% in science

Upvotes: 0

nicola
nicola

Reputation: 24480

If you just need to add a backslash to the characters contained in the a vector, then you can try in base R:

gsub(paste0("(",paste(a,collapse="|"),")"),"\\\\\\1",v1)

Too bad that only 6(!) consecutive backslashes are needed to perform the task.

Upvotes: 1

akrun
akrun

Reputation: 886948

We can use mgsub from qdap

library(qdap)
mgsub(a, b, v1)

data

v1 <- c('I got 95% in maths & 80% in science',
        'He got 90% in maths & 70% in science')
b <- c('\\%', '\\&')

Upvotes: 2

Related Questions