How to sort a data frame in R

I am new to R, and want to sort a data frame called "weights". Here are the details:

>str(weights)
'data.frame':   57 obs. of  1 variable:
 $ attr_importance: num  0.04963 0.09069 0.09819 0.00712 0.12543 ...

> names(weights)
  [1] "attr_importance"

> dim(weights)
  [1] 57  1

> head(weights)
        attr_importance
make        0.049630556
address     0.090686474
all         0.098185517
num3d       0.007122618
our         0.125433292
over        0.075182467

I want to sort by decreasing order of attr_importance BUT I want to preserve the corresponding row names also.

I tried:

> weights[order(-weights$attr_importance),]

but it gives me a "numeric" back.

I want a data frame back - which is sorted by attr_importance and has CORRESPONDING row names intact. How can I do this?

Thanks in advance.


Solution 1:

Since your data.frame only has one column, you need to set drop=FALSE to prevent the dimensions from being dropped:

weights[order(-weights$attr_importance),,drop=FALSE]
#         attr_importance
# our         0.125433292
# all         0.098185517
# address     0.090686474
# over        0.075182467
# make        0.049630556
# num3d       0.007122618

Solution 2:

Here is the big comparison on data.frame sorting:

How to sort a dataframe by column(s)?

Using my now-preferred solution arrange:

dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"), 
      levels = c("Low", "Med", "Hi"), ordered = TRUE),
      x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
      z = c(1, 1, 1, 2))
library(plyr)
arrange(dd,desc(z),b)
    b x y z
1 Low C 9 2
2 Med D 3 1
3  Hi A 8 1
4  Hi A 9 1