Search code examples
rsortingstring-operations

r - How to sort words in a string?


Let's say I have a dataframe of strings.

Each string is a series of numbers; there could be any quantity of numbers in each string.

How can I re-sort those numbers within the string?

input <- data.frame(id = c(1,2,3),str = c('400','201 17','30 1 5'),stringsAsFactors=FALSE)

desired_out <- data.frame(id = c(1,2,3),str = c('400','17 201','1 5 30'),stringsAsFactors=FALSE)

If it helps, I'm not picky numerical vs. character sorting - i.e. I don't care if '201 21 11' gets sorted to '11 21 201' or '11 201 21', as long as it gets sorted consistently.


Solution

  • Split the elements of input$str, convert them to numeric, sort them, and paste them back together

    input <- data.frame(id = c(1,2,3),str = c('400','201 17','30 1 5'),stringsAsFactors=FALSE)
    input$new_str = sapply(input$str, function(x)
        paste(sort(as.numeric(unlist(strsplit(x, " ")))), collapse = " "))
    input
    #  id    str new_str
    #1  1    400     400
    #2  2 201 17  17 201
    #3  3 30 1 5  1 5 30