how to change order of words before and after underscore
For example
- hello_wor -> wor_hello
- 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"