“last name, first name” -> “first name last name” in serialized strings

前端 未结 3 445
慢半拍i
慢半拍i 2021-01-13 00:14

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         


        
3条回答
  •  隐瞒了意图╮
    2021-01-13 01:00

    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"    
    

提交回复
热议问题