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?
If we have string data stored in R data frame columns then we might want to sort the data frame rows in alphabetical order. This can be done with the help of apply and sort function inside transpose function.
To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.
To sort a vector in R programming, call sort() function and pass the vector as argument to this function. sort() function returns the sorted vector in increasing order. The default sorting order is increasing order. We may sort in decreasing order using rev() function on the output returned by sort().
Methods to sort a dataframe:order() function (increasing and decreasing order) arrange() function from dplyr package. setorder() function from data. table package.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With