如何在R中对数据框进行排序 [英] How to sort a data frame in R

查看:513
本文介绍了如何在R中对数据框进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 > str(weights)
'data.frame':57 obs。的1个变量:
$ attr_importance:num 0.04963 0.09069 0.09819 0.00712 0.12543 ...

>名称(重量)
[1]attr_importance

>昏暗(重量)
[1] 57 1

>头(重量)
attr_importance
make 0.049630556
地址0.090686474
全部0.098185517
num3d 0.007122618
我们的0.125433292
超过0.075182467

我想按照attr_importance的递减顺序排序,但是我也想保留相应的行名。



我试过:

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

但它给了我一个数字的回来。



我想要一个数据框,它是由attr_importance排序的,并且具有完整的CORRESPONDING行名称。如何做到这一点?



提前感谢

解决方案

由于您的data.frame只有一列,您需要设置 drop = FALSE 以防止维度被删除:

  weight [order(-weights $ attr_importance),, drop = FALSE] 
#attr_importance
#我们的0.125433292
#全部0.098185517
#address 0.090686474
#over 0.075182467
#make 0.049630556
#num3d 0.007122618


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.

解决方案

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

这篇关于如何在R中对数据框进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆