(1) Maintain the same name in each element . This can be done with a single gsub (if there are no commas in the names):
> gsub("([^, ][^,]*), ([^,]+)", "\\2 \\1", names) [1] "Simon Beaufoy, Danny Boyle" "Christopher Nolan" [3] "Stuart Blumberg, Lisa Cholodenko" "David Seidler" [5] "Aaron Sorkin" > gsub("([^, ][^,]*), ([^,]+)", "\\2 \\1", "Hoover, J. Edgar") [1] "J. Edgar Hoover"
(2) Divide by one name for each item . If you need each last name of the name in a separate element, use (a) scan
scan(text = out, sep = ",", what = "")
where out is the result of the above gsub or for its direct use. (b) bind :
> library(gsubfn) > strapply(names, "([^, ][^,]*), ([^,]+)", x + y ~ paste(y, x), simplify = c) [1] "Simon Beaufoy" "Danny Boyle" "Christopher Nolan" [4] "Stuart Blumberg" "Lisa Cholodenko" "David Seidler" [7] "Aaron Sorkin" > strapply("Hoover, Edgar J.", "([^, ][^,]*), ([^,]+)", x + y ~ paste(y, x), + simplify = c) [1] "Edgar J. Hoover"
Note that all the examples above used the same regular expression for matching.
UPDATE: The remote comma separating the first and last name.
UPDATE: code has been added to split the name of each surname into a separate element in the event that this is the preferred output format.