用R中的其他特殊字符替换特殊字符

Replace special characters with other special character in R

我想将一些特殊字符删除为其他一些特殊字符。这里有两个向量。

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

我想将向量 a 的元素替换为向量 v1 中向量 b 的对应元素。

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

我尝试了 gsub 但没有成功。 此外,我无法创建向量 b,因为它给出了以下错误。

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

我们可以使用 mgsub 来自 qdap

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

数据

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

如果只需要在a vector中包含的字符添加反斜杠,那么可以尝试在base R:

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

太糟糕了,只需要 6(!)个连续的反斜杠就可以完成任务。

该错误是由于您的对象 b 中的 \ 未被转义而产生的。如下所示尝试,它将起作用。请注意,字符串本身使用 cat() 显示为单个反斜杠,但会同时打印这两个反斜杠。在R字符对象中定义一个\,需要转义

请注意,为了对 a 中的每个元素对 b 中的每个元素进行矢量化替换,我使用了 stringi,这非常适合矢量化替换。

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