Is gsub () all but the specified characters?

How can I use gsub () all but the specified character in R?

In my problem, I have the following line ...

"the quick brown fox jumps over a lazy dog"

I need to generate a new line by deleting all characters except "r" and "o", and we get the following output ...

"roooro"

Assuming all characters are lowercase, how should I go. I tried...

gsub(!"r","",gsub(!"o","",str1))

But '!' does not work.

+4
source share
1 answer

We need to use ^inside [to match all characters except ro. This [^ro]+involves matching one or more characters that are not "r" or "o", and replace it with an empty ( "").

gsub("[^ro]+", "", str1)
#[1] "roooro"

, paste

v1 <- c("r", "o")
gsub(paste0("[^", paste(v1, collapse=""), "]+"), "", str1)
#[1] "roooro"
+5

Source: https://habr.com/ru/post/1649855/


All Articles