“姓,名"->“名字姓氏"在序列化字符串中 [英] "last name, first name" -> "first name last name" in serialized strings

查看:63
本文介绍了“姓,名"->“名字姓氏"在序列化字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆字符串,其中包含姓,名格式的名称列表,以逗号分隔,如下所示:

I have a bunch of strings that contain lists of names in last name, first name format, separated by commas, like so:

names <- c('Beaufoy, Simon, Boyle, Danny','Nolan, Christopher','Blumberg, Stuart, Cholodenko, Lisa','Seidler, David','Sorkin, Aaron')

将字符串中的所有这些姓名转换为名字姓氏格式的最简单方法是什么?

What's the easiest way to convert all these names within the strings to first name last name format?

推荐答案

如果您可以确定逗号不会出现在一个人的名字中,这可能会起作用:

If you can be certain that a comma isn't going to be in a person's name, this might work:

mynames <- c('Beaufoy, Simon, Boyle, Danny',
             'Nolan, Christopher',
             'Blumberg, Stuart, Cholodenko, Lisa',
             'Seidler, David',
             'Sorkin, Aaron',
             'Hoover, J. Edgar')
mynames2 <- strsplit(mynames, ", ")

unlist(lapply(mynames2, 
              function(x) paste(x[1:length(x) %% 2 == 0], 
                                x[1:length(x) %% 2 != 0])))
# [1] "Simon Beaufoy"     "Danny Boyle"       "Christopher Nolan"
# [4] "Stuart Blumberg"   "Lisa Cholodenko"   "David Seidler"    
# [7] "Aaron Sorkin"      "J. Edgar Hoover"        

我已经在那里添加了 J. Edgar Hoover,这是很好的衡量标准.

I've added J. Edgar Hoover in there for good measure.

如果您希望引用在一起的名称保持在一起,请将 collapse = ", " 添加到您的 paste() 函数中:

If you want the names that were quoted together to stay together, add collapse = ", " to your paste() function:

unlist(lapply(mynames2, 
              function(x) paste(x[1:length(x) %% 2 == 0], 
                                x[1:length(x) %% 2 != 0],
                                collapse = ", ")))
# [1] "Simon Beaufoy, Danny Boyle"       "Christopher Nolan"               
# [3] "Stuart Blumberg, Lisa Cholodenko" "David Seidler"                   
# [5] "Aaron Sorkin"                     "J. Edgar Hoover"    

这篇关于“姓,名"-&gt;“名字姓氏"在序列化字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆