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
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"
I've added J. Edgar Hoover in there for good measure.
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"