Changing “firstname lastname” to “lastname, firstname”

妖精的绣舞 提交于 2021-02-09 11:10:38

问题


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.


回答1:


Use

gsub("(.*[^van])\\s(.*)", "\\2, \\1", people)

The regex:

(.*[^van])                                         \\s                      (.*)
Any ammount of characters exluding "van"...  the last white space...  The last name containing any character.

Data:

people <- c("Barack Obama",
            "Donald J. Trump",
            "J. Edgar Hoover",
            "Beyonce Knowles-Carter",
            "Sting",
            "Ruud van Nistelrooy",
            "Xi Jinping",
            "Hans Zimvanmer")

Result:

    [1] "Obama, Barack"           "Trump, Donald J."        "Hoover, J. Edgar"       
[4] "Knowles-Carter, Beyonce" "Sting"                   "van Nistelrooy, Ruud"   
[7] "Jinping, Xi"             "Zimvanmer, Hans" 



回答2:


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" 


来源:https://stackoverflow.com/questions/53672694/changing-firstname-lastname-to-lastname-firstname

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!