vagabond
vagabond

Reputation: 3594

change position of word within a string in r

I have a string vector that looks like:

> string_vec
 [1] "XXX"                     "Snakes On A Plane"       "Mask of the Ninja"       "Ruslan"                 
 [5] "Kill Switch"             "Buddy Holly Story, The"  "Believers, The"          "Closet, The"            
 [9] "Eyes of Tammy Faye, The" "Gymnast, The"            "Hunger, The" 

There are some names which contain ", The" in the end. I want to delete the comma and the space and move the "The" before all other text.

For e.g.: "Buddy Holly Story, The" becomes "The Buddy Holly Story".

Isolating the records with the pattern was easy :

string_vec[grepl("[Aa-zZ]+, The", string_vec) == TRUE]

How can I adjust the position now?

data

string_vec <- c("XXX", "Snakes On A Plane", "Mask of the Ninja", 
"Ruslan", 
"Kill Switch", "Buddy Holly Story, The", "Believers, The", 
"Closet, The", 
"Eyes of Tammy Faye, The", "Gymnast, The", "Hunger, The")

Upvotes: 9

Views: 2490

Answers (1)

akrun
akrun

Reputation: 887981

You may try

sub('^(.*), The', 'The \\1', string_vec)
#[1] "XXX"                    "Snakes On A Plane"      "Mask of the Ninja"     
#[4] "Ruslan"                 "Kill Switch"            "The Buddy Holly Story" 
#[7] "The Believers"          "The Closet"             "The Eyes of Tammy Faye"
#[10] "The Gymnast"            "The Hunger"  

Upvotes: 15

Related Questions