Home > Mobile >  Order alphabetically each element of a list in R
Order alphabetically each element of a list in R

Time:12-17

I have a dataframe and one of the variables is a list. I want each of the vectors in the list to be alphabetically ordered.

[1] F,D should become D,D

[2] B,D,C should become B,C,D

and son on with each row

I have tried DF$variableC<-lapply(DF$variable, sort) but nothing happens, the variable remains exactly the same

CodePudding user response:

One base R approach would be to split the CSV input string into a list, sort that list, then paste collapse back to CSV.

x <- "B,D,C"
output <- paste(lapply(strsplit(x, ","),sort)[[1]], collapse=",")
output

[1] "B,C,D"

CodePudding user response:

Alternatives in case TimBiegeleisen's assumption of vector-of-strings is not correct:

List of strings (instead of vector of strings ... barely a difference).

L <- list("F,D", "B,D,C")
lapply(L, function(z) paste(sort(strsplit(z, ",")[[1]]), collapse = ","))
# [[1]]
# [1] "D,F"
# [[2]]
# [1] "B,C,D"

or a list of vectors:

L <- list(c("F","D"), c("B","D","C"))
lapply(L, sort)
# [[1]]
# [1] "D" "F"
# [[2]]
# [1] "B" "C" "D"
  • Related