简体   繁体   中英

How to replace characters contained in a vector with another single character using R

I have the following string:

x <- "KDDADQHRQDKWKDEHENRFKDEFVDEKKK"

What I want to do is to replace character in that string with ? if they are contained in this vector:

repo <- c("R", "H", "K", "D", "E")

Resulting in this:

???A?QHRQ??W?????N?F???FV?????

I also want the negation version, meaning replace everything that is NOT in repo with ? .

Resulting in KDD?D?HR?DK?KDEHE?R?KDE??DEKKK

How can I achieve that with R?

We can use gsub() with a regex character class:

x <- "KDDADQHRQDKWKDEHENRFKDEFVDEKKK"
repo <- c("R", "H", "K", "D", "E")
regex = paste0("[", paste(repo, collapse=""), "]")
output <- gsub(regex, "?", x)
output

[1] "???A?Q??Q??W?????N?F???FV?????"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM