我有一堆字符串,包含姓氏,名字格式的名字列表,用逗号分隔,如下所示:
names <- c('Beaufoy,Simon,Boyle,Danny','Nolan,Christopher','Blumberg,Stuart,Cholodenko,Lisa','Seidler,David','Sorkin,Aaron')
如果你可以确定一个逗号不是一个人的名字,这可能会有效:
mynames <- c('Beaufoy,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.
如果您希望一起引用的名称保持在一起,请将fold =“,”添加到您的paste()函数中:
unlist(lapply(mynames2,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"