10

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.

Jeff Atwood
  • 60,897
  • 45
  • 146
  • 152
user721975
  • 1,115
  • 3
  • 12
  • 14
  • 5
    @Jeff Atwood : Not that it matters now, but the questions are not duplicates at all. My question is more like "how to sort while preserving row names" while the one that you refer to is "how to sort by multiple columns". – user721975 Aug 01 '11 at 12:12
  • ok, reopened then -- apologies – Jeff Atwood Aug 01 '11 at 18:59

3 Answers3

10

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
Joshua Ulrich
  • 163,034
  • 29
  • 321
  • 400
9

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
Community
  • 1
  • 1
Ari B. Friedman
  • 66,857
  • 33
  • 169
  • 226
0

rankdata.txt

regno   name           total    maths   science social cat
1   SUKUMARAN   400 78  89  73  S
2   SHYAMALA    432 65  79  87  S
3   MANOJ       500 90  129 78  C
4   MILYPAULOSE 383 59  88  65  G
5   ANSAL       278 39  77  60  O
6   HAZEENA     273 45  55  56  O
7   MANJUSHA    374 50  99  52  C
8   BILBU       408 81  97  72  S
9   JOSEPHROBIN 374 57  85  68  G
10  SHINY       381 70  79  70  S
z <- data.frame(rankdata)

z[with(z, order(-total+ maths)),]  #order function  maths group selection
z
z[with(z, order(name)),]  # sort on name
z
scoa
  • 17,192
  • 4
  • 56
  • 75