[英]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
向量,那么你可以嘗試在基地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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.