Replace space between two words with an underscore in a vector

前端 未结 2 645
慢半拍i
慢半拍i 2021-01-18 17:08

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
         


        
相关标签:
2条回答
  • 2021-01-18 17:30

    You should use gsub:

    data$species <- gsub(" ", "_", data$species)
    
    0 讨论(0)
  • 2021-01-18 17:45

    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, " ", "_"))
    
    0 讨论(0)
提交回复
热议问题