PAC PAC - 1 month ago 5
R Question

How to sort a data frame by alphabetic order of a character variable in R?

I would like to sort a data frame by alphabetic order of a character variable in R. I've tried to do it with the order() function but it transforms my data frame into a list. Does anyone has a clue ?

Answer

Well, I've got no problem here :

df <- data.frame(v=1:5, x=sample(LETTERS[1:5],5))
df

#   v x
# 1 1 D
# 2 2 A
# 3 3 B
# 4 4 C
# 5 5 E

df <- df[order(df$x),]
df

#   v x
# 2 2 A
# 3 3 B
# 4 4 C
# 1 1 D
# 5 5 E
Comments