从字符向量中删除中间名,首字母或什么都不要 [英] Remove middle name, initial, or nothing from character vector

查看:81
本文介绍了从字符向量中删除中间名,首字母或什么都不要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的名字向量:

I have a vector of names like so:

x <- c("bob smith", "greg a taylor", "lindsey louise brown")

所以每个条目都是名字的姓氏,两者之间没有任何关系,或中间名的首字母或整个中间名。我想做的是删除有关中间名的信息,所以我应该得到

so each entry is a name firstname lastname with either nothing between, or a middle initial or the whole middle name. What I want to do is remove the information about the middle name where it exists, so I should get

"bob smith", "greg taylor", "lindsey brown"

作为输出。在R中这怎么可能?

as the output. How is this possible in R?

谢谢!

推荐答案

我们可以使用捕获组

sub('^(\\w+).*\\b(\\w+)$', '\\1 \\2', x)
#[1] "bob smith"     "greg taylor"   "lindsey brown"

这篇关于从字符向量中删除中间名,首字母或什么都不要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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