Removing special characters and spaces from strings

Viewed 269
name1 <- "Adam & Eve"
name2 <- "Spartacus"
name3 <- "Fitness and Health"

I want to remove all spaces and special characters such as %&,. and the word and between the names, and then capitalize each string, so the names become:

name1 <- "ADAMEVE"
name2 <- "SPARTACUS"
name3 <- "FITNESSHEALTH"
3 Answers

We can use sub to remove the and string, then with gsub remove everything other (^) than the letters (upper, lower case) and convert the case to upper (toupper)

f1 <- function(x) toupper(gsub("[^A-Za-z]", "", sub("and", "", x, fixed = TRUE)))

-testing

> f1(name1)
[1] "ADAMEVE"
> f1(name2)
[1] "SPARTACUS"
> f1(name3)
[1] "FITNESSHEALTH"

Inspired by akrun's answer we could create a function and apply it to the vectors:

library(stringr)
my_function <- function(x){
    x <- str_replace_all(x, "[^A-Za-z0-9]","")
    x <- toupper(x)
    x <- str_remove_all(x, "AND")
    return(x)
}

my_function(c(name1, name2,name3))

Output:

[1] "ADAMEVE"       "SPARTACUS"     "FITNESSHEALTH"

You can use stringr with str_remove_all() and the patterns for "any non-word characters" ("\\D"), and the word "and" (use word boundaries here, \\b), and then change all to upper case with toupper()

library(stringr)

name1 %>% str_remove_all("\\D|\\band\\b") %>% toupper

If you want do define a function for that, you can do it as follows:

my_function <- function(x) { x %>% str_remove_all ("\\D|\\band\\b") %>% toupper }
Related