按行排序数据 [英] Sort data by row

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

问题描述

我有一个类似的数据框

Id  A B C D E F
a   1 2 9 4 7 6
b   4 5 1 3 6 10
c   1 6 0 3 4 5

我想要一个数据框

Id
a  C E F D B A     #for a, C has the highest value, then E then F and so on...similarly for other rows
b  F E B A D C
c  B F E D A C

基本上,我先对数据帧的每一行进行排序,然后用相应的列名替换行值.

Basically, i am sorting each row of the data frame first and then replacing row values by the respective column names.

有什么好办法吗?

推荐答案

orderapply结合使用,在过程中提取names,如下所示:

Use order with apply, extracting the names in the process, like this:

data.frame(
  mydf[1], 
  t(apply(mydf[-1], 1, function(x) 
    names(x)[order(x, decreasing = TRUE)])))
#   Id X1 X2 X3 X4 X5 X6
# 1  a  C  E  F  D  B  A
# 2  b  F  E  B  A  D  C
# 3  c  B  F  E  D  A  C

apply的结果需要重新放置t才能与 Id 列重新组合.

The result of apply needs to be transposed before it is recombined with the Id column.

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

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