I have a string variable. I want to find a dplyr way to move the words in trail from string to the beginning of the string and remove it from the end, as in goal.
Anyone knows how to do this?
Thank you!
string <- as.data.frame(c("ABA PRIMARY SCHOOL", "BLABLA SECONDARY SCHOOL", "WAZA INSTITUT", "INSTITUT WAMA", "PRIMARY SCHOOL WAMA"))
trail = c(" PRIMARY SCHOOL", " SECONDARY SCHOOL", " INSTITUT")
goal <- as.data.frame(c("PRIMARY SCHOOL ABA", "SECONDARY SCHOOL BLABLA", "INSTITUT WAZA", "INSTITUT WAMA", "PRIMARY SCHOOL WAMA"))
CodePudding user response:
Here is an option using dplyr and stringr.
library(dplyr)
library(stringr)
df %>%
mutate(temp = str_extract(string, str_c(trail, collapse = '|')),
result = ifelse(is.na(temp), string, str_c(temp, str_remove(string, temp), sep = ' '))) %>%
select(-temp)
# string result
#1 ABA PRIMARY SCHOOL PRIMARY SCHOOL ABA
#2 BLABLA SECONDARY SCHOOL SECONDARY SCHOOL BLABLA
#3 WAZA INSTITUT INSTITUT WAZA
#4 INSTITUT WAMA INSTITUT WAMA
#5 PRIMARY SCHOOL WAMA PRIMARY SCHOOL WAMA
data
string <- c("ABA PRIMARY SCHOOL", "BLABLA SECONDARY SCHOOL", "WAZA INSTITUT", "INSTITUT WAMA", "PRIMARY SCHOOL WAMA")
df <- data.frame(string)
trail = c(" PRIMARY SCHOOL", " SECONDARY SCHOOL", " INSTITUT")
