如何在R中对数据框进行排序

13

我是R语言的新手,想要对名为“weights”的数据框进行排序。以下是详细信息:

>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排序,并保持相应的行名不变。我该如何做到这一点?提前致谢。

5
并不是现在有多大关系,但这两个问题并不重复。我的问题更像是“如何在保留行名称的同时进行排序”,而你提到的那个问题是“如何按多列排序”。 - user721975
好的,那就重新开启吧 -- 抱歉。 - Jeff Atwood
3个回答

14

由于您的数据框只有一列,因此需要设置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

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

11

下面是对data.frame排序的详细比较:

如何按列排序数据框?

我现在偏好使用 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

1

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接