9

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")
0

1 Answer 1

15

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"  
13
  • this works! thanks. I didn't know the \\1 can be used to refer to position within string in regex.
    – vagabond
    May 5, 2015 at 14:41
  • @vagabond We are capturing the group before the , The and use that to replace \\1
    – akrun
    May 5, 2015 at 14:42
  • 1
    @vagabond That is the first capture group inside the parentheses. Suppose if there are two capture groups, we refer it as \\1 \\2 and so on. For example, sub('^(.*), (The)', '\\2 \\1', string_vec) , here The is the second capture group
    – akrun
    May 5, 2015 at 14:44
  • 1
    If you need the first word, try word(string_vec,1) or sub('^(\\w+).*$', '\\1', string_vec)
    – akrun
    May 5, 2015 at 14:53
  • 1
    @vagabond Or sub('[^A-Za-z]+.*$', '', string_vec)
    – akrun
    May 5, 2015 at 14:57

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.