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

前端 未结 3 548
慢半拍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

    I'm in favor of @AnandaMahto's Answer, but just for fun, this illustrates another method using scan, split, and rapply.

    names <- c(names, 'Chambers, John, Ihaka, Ross, Gentleman, Robert')
    
    # extract names
    snames <- 
    lapply(names, function(x) scan(text=x, what='', sep=',', strip.white=TRUE, quiet=TRUE))
    
    # break up names
    snames<-lapply(snames, function(x) split(x, rep(seq(length(x) %/% 2), each=2)))
    
    # collapse together, reversed
    rapply(snames, function(x) paste(x[2:1], collapse=' '))
    

提交回复
热议问题