使用ifelse命令进行字符串解析



我在将一系列名称解析为名字和姓氏时遇到问题。给出一个名称列表,如下所示:

names <- as.vector(c("Rep. Mike Grimm","House Committee on Energy and Commerce",
                 "Office of the Inspector General","Rep. J. Gresham Barrett","Rep. Mary Fallin"))

如何为sub编写正则表达式代码,以仅提取列表中以"Rep"开头的名称的名字和姓氏?因此,我认为我需要编写一个正则表达式代码,只从以"Rep"开头的名称中提取第二个单词,只提取另一列的第三个单词,因为我想为名字创建一列,为姓氏创建另一列。我尝试了许多正则表达式代码,但找不到一个有效的。谢谢大家的帮助!

ans <- gsub('Rep. ', '', names[grep('Rep. ', names)])
First <- gsub('\s\w+$', '', ans)
Last <- gsub('.*?(\w+$)', '\1', ans)
df <- data.frame(First, Last)
df
#       First    Last
#1       Mike   Grimm
#2 J. Gresham Barrett
#3       Mary  Fallin

这就是你的想法吗?我不会将对象命名为"名称",因为你会屏蔽函数"名称"

names.of <- as.vector(c("Rep. Mike Grimm","House Committee on Energy and Commerce",
                  "Office of the Inspector General","Rep. J. Gresham Barrett","Rep. Mary Fallin"))
names.rep<-grep("Rep",names.of,value=T )
gsub("Rep\. ([A-Za-z]+)","\1",names.rep)

最新更新