Search code examples
rdataframealphabetized

How do I alphabetize comma-separated values in a dataframe?


I have a dataframe in R as shown in the first table below. I would like to alphabetize the comma-separated values within each cell for specified columns (Q1, Q2, etc) so that it results in a dataframe as shown in the second table below.

id Q1 Q2
1 alpha,charlie,apple B,D,C,A
2 zulu,delta,bravo D,A,C,B
id Q1 Q2
1 alpha,apple,charlie A,B,C,D
2 bravo,delta,zulu A,B,C,D

Solution

  • We could split both the columns, do the sorting and then paste back

    library(dplyr)
    library(purrr)
    df1 %>%
        mutate(across(c(Q1, Q2), ~ map_chr(strsplit(., ","), ~ toString(sort(.x)))))
    

    -output

    id                    Q1         Q2
    1  1 alpha, apple, charlie A, B, C, D
    2  2    bravo, delta, zulu A, B, C, D
    

    data

    df1 <- structure(list(id = 1:2, Q1 = c("alpha,charlie,apple", "zulu,delta,bravo"
    ), Q2 = c("B,D,C,A", "D,A,C,B")), class = "data.frame", row.names = c(NA, 
    -2L))