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