Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing "firstname lastname" to "lastname, firstname"

Tags:

string

regex

r

I have a list of names that I need to convert from "Firstname Lastname" to "Lastname, Firstname".

Barack Obama
Donald J. Trump
J. Edgar Hoover
Beyonce Knowles-Carter
Sting

I used G. Grothendieck's answer to "last name, first name" -> "first name last name" in serialized strings to get to gsub("([^ ]*) ([^ ]*)", "\\2, \\1", str) which gives me -

Obama, Barack
J., DonaldTrump, 
Edgar, J.Hoover, 
Knowles-Carter, Beyonce
Sting

What I would like to get -

Obama, Barack
Trump, Donald J. 
Hoover, J. Edgar
Knowles-Carter, Beyonce
Sting

I would like a regex answer.

like image 682
phil_t Avatar asked Nov 17 '25 16:11

phil_t


1 Answers

There is an esoteric function called person designed for holding names, a conversion function as.person which does this parsing for you and a format method to make use of it afterwards (with a creative use of the braces argument). It even works with complex surnames (eg van Nistelrooy) but the single name result is unsatisfactory. It can fixed with a quick ending sub though.

x <- c("Barack Obama","Donald J. Trump","J. Edgar Hoover","Beyonce Knowles-Carter","Sting", "Ruud van Nistelrooy", "John von Neumann")
y <- as.person(x)

format(y, include=c("family","given"), braces=list(family=c("",",")))
[1] "Obama, Barack"           "Trump, Donald J."       
[3] "Hoover, J. Edgar"        "Knowles-Carter, Beyonce"
[5] "Sting,"                  "van Nistelrooy, Ruud"   
[7] "von Neumann, John"

## fix for single names - curse you Sting!

sub(",$", "", format(y, include=c("family","given"), braces=list(family=c("",","))))
[1] "Obama, Barack"           "Trump, Donald J."       
[3] "Hoover, J. Edgar"        "Knowles-Carter, Beyonce"
[5] "Sting"                   "van Nistelrooy, Ruud"   
[7] "von Neumann, John" 
like image 118
James Avatar answered Nov 19 '25 07:11

James