Replace space between two words with an underscore in a vector

Viewed 21766

I have words, Genus species, and I want an underscore to replace the space between the two strings in R

Input:

>data$species
Genus species

Desired output:

>data$species
Genus_species
3 Answers

We can use sub from base R

data$species <- sub(" ", "_", data$species)

Or with chartr from base R

data$species <- chartr(" ", "_", data$species)

Or using tidyverse

library(tidyverse)
data %>%
    mutate(species = str_replace(species, " ", "_"))

You should use gsub:

data$species <- gsub(" ", "_", data$species)

The pattern [^[:alnum:]] can be used to replace all non alphanumeric characters by underscores. Combine it with tolower() to convert all characters to snake case following the tidyverse syntax recommendations.

column_names <- c("Bla Bla", "Hips / Hops", "weight (1000 kg)")
gsub("[^[:alnum:]]", "_", tolower(column_names))

[1] "bla_bla"          "hips___hops"      "weight__1000_kg_"

The pattern [^[:alnum:]]+ replaces one or more occurrences by an underscore.

gsub("[^[:alnum:]]+","_",tolower(column_names))

[1] "bla_bla"         "hips_hops"       "weight_1000_kg_"

See help(regexp) for more information on regular expressions.

Related