Replace multiple lines in a single gsub () or chartr () expression with R?

I have a string variable containing the alphabet [az], space [] and apostrophe ['], for example. x <- "a'b c" I want to replace the apostrophe ['] with an empty [] and replace the space [] with an underscore [_].

 x <- gsub("'", "", x) x <- gsub(" ", "_", x) 

It works absolutely, but when I have a lot of conditions, the code gets ugly. So I want to use chartr() , but chartr() cannot handle space, for example.

 x <- chartr("' ", "_", x) #Error in chartr("' ", "_", "a'b c") : 'old' is longer than 'new' 

Is there any way to solve this problem? thanks!

+13
string r gsub
source share
5 answers

You can use gsubfn

 library(gsubfn) gsubfn(".", list("'" = "", " " = "_"), x) # [1] "ab_c" 

Similarly, we can also use mgsub which allows multiple replacements with multiple templates.

 mgsub::mgsub(x, c("'", " "), c("", "_")) #[1] "ab_c" 
+13
source share

I am a fan of the syntax that the %<>% and %>% operators from the magrittr package magrittr .

 library(magrittr) x <- "a'b c" x %<>% gsub("'", "", .) %>% gsub(" ", "_", .) x ##[1] "ab_c" 

gusbfn great, but I like the %>% binding.

+16
source share

I would choose magrittr and / or dplyr . However, I prefer not to create a new copy of the object, especially if it is in a function and can be returned cheaply.

i.e.

 return( catInTheHat %>% gsub('Thing1', 'Thing2', .) %>% gsub('Red Fish', 'Blue Fish', .) ) 

... etc.

+2
source share
 gsub("\\s", "", chartr("' ", " _", x)) # Use whitespace and then remove it 
+1
source share

I think nested gsub will do the job.

 gsub("Find","Replace",gsub("Find","Replace",X)) 
+1
source share

All Articles