user4400727
user4400727

Reputation:

Replace space between two words with an underscore in a vector

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

Upvotes: 16

Views: 42520

Answers (3)

Paul Rougieux
Paul Rougieux

Reputation: 11409

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.

Upvotes: 5

akrun
akrun

Reputation: 887541

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, " ", "_"))

Upvotes: 26

gaut
gaut

Reputation: 5958

You should use gsub:

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

Upvotes: 14

Related Questions