I have a string variable containing alphabet[a-z], space[ ], and apostrophe['],eg. x <- "a'b c"
I want to replace apostrophe['] with blank[], and replace space[ ] with underscore[_].
x <- gsub("'", "", x) x <- gsub(" ", "_", x)
It works absolutely, but when I have a lot of condition, the code becomes ugly. Therefore, I want to use chartr()
, but chartr()
can't deal with blank, eg.
x <- chartr("' ", "_", x) #Error in chartr("' ", "_", "a'b c") : 'old' is longer than 'new'
Is there any way to solve this problem? thanks!
Use str_replace_all() method of stringr package to replace multiple string values with another list of strings on a single column in R and update part of a string with another string.
gsub() function in R Language is used to replace all the matches of a pattern from a string. If the pattern is not found the string will be returned as it is. Syntax: gsub(pattern, replacement, string, ignore.case=TRUE/FALSE)
Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.
The sub() and gsub() function in R is used for substitution as well as replacement operations. The sub() function will replace the first occurrence leaving the other as it is. On the other hand, the gsub() function will replace all the strings or values with the input strings.
You can use gsubfn
library(gsubfn) gsubfn(".", list("'" = "", " " = "_"), x) # [1] "ab_c"
Similarly, we can also use mgsub
which allows multiple replacement with multiple pattern to search
mgsub::mgsub(x, c("'", " "), c("", "_")) #[1] "ab_c"
I am a fan of the syntax that the %<>%
and %>%
opperators from the magrittr
package provide.
library(magrittr) x <- "a'b c" x %<>% gsub("'", "", .) %>% gsub(" ", "_", .) x ##[1] "ab_c"
gusbfn
is wonderful, but I like the chaining %>%
allows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With