2011-08-01 78 views
6

我是R新手,想要对称为“权重”的数据帧进行排序。以下是详细信息:如何排序R中的数据帧

>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 

我想按降序顺序排列attr_importance但我想保留相应的行名称也。

我想:

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

,但它给了我一个 “数字” 了。

我想要一个数据框 - 它是按attr_importance排序的,并且有相应的行名完好无损。我怎样才能做到这一点?

在此先感谢。

+4

@Jeff阿特伍德:不,现在的问题,但这些问题不重复的。我的问题更像是“如何在保留行名的同时进行排序”,而你所指的是“如何按多列排序”。 – user721975

+0

好吧,重新打开然后 - 道歉 –

回答

8

由于您的data.frame只有一列,你需要设置drop=FALSE防止尺寸而落下:

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 
+1

得到它感谢。我的头正在旋转。男人,R很难学:-( – user721975

+1

drop = FALSE是我忘记的修复:) – neilfws

+0

你救了我!有趣的是,sort()函数不保留行名称! – weber85

9

这里是data.frame排序大比较:

How to sort a dataframe by column(s)?

用我现在-首选方案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 
+0

整洁的trick.thanks。 – user721975

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