Home > database >  how to change the order of words before and after underscore in R
how to change the order of words before and after underscore in R

Time:10-31

how to change order of words before and after underscore

For example

  1. hello_wor -> wor_hello
  2. hi_everyone -> everyone_hi

CodePudding user response:

We can use regex to do this i.e. capture the words ((\\w )) before and after the _ and in the replacement rearrange the backreferences

sub("^(\\w )_(\\w )$", "\\2_\\1", str1)
[1] "wor_hello"   "everyone_hi"

data

str1 <- c("hello_wor", "hi_everyone")

CodePudding user response:

We could do:

sub("(.*)_(.*)", "\\2_\\1", str1)
[1] "wor_hello"   "everyone_hi"

CodePudding user response:

With tidyverse approach:

library(tidyverse)

words <- c("Peter_Gabriel", "Tina_Turner")

map_chr(words, ~ str_extract_all(.x, "\\w (?=_)|(?<=_)\\w ") 
    %>% flatten %>% rev %>% paste0(collapse = "_"))

#> [1] "Gabriel_Peter" "Turner_Tina"
  •  Tags:  
  • r
  • Related