R中的排名行 [英] Ranking rows in R

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

问题描述

我有一个包含多列(针对不同站点)和多行(针对不同日期)的值数据集,我尝试使用 R 对每天的数据进行排名.我希望对每列(站点)的数据进行排名来自一天内的网站总数(因此排名基于每一行).可以在 Excel 中进行,但显然需要很长时间.下面是我试图实现的[更小]示例:

I have a dataset of values that has multiple columns (for different sites) and rows (for different days) that I am trying to rank for each day using R. I would like the rank the data for each column (site) from the total number of sites within one day (so ranking based on each row). It would be possible to do in Excel, but would obviously take a long time. Below is a [much smaller] example of what i'm trying to achieve:

date - site1 - site2 - site3 - site4
1/1/00 - 24 - 33 - 10 - 13
2/1/00 - 13 - 25 - 6 - 2
~~ leading to:
date - site1 - site2 - site3 - site4
1/1/00 - 2 - 1 - 4 - 3
2/1/00 - 2 - 1 - 3 - 4

希望有一些简单的命令,非常感谢!

hopefully there's some simple command, thanks a lot!

推荐答案

您可以使用 rank 来给出数据的排名.

You can use rank to give the ranks of the data.

# your data
mydf <- read.table(text="date - site1 - site2 - site3 - site4
1/1/00 - 24 - 33 - 10 - 13
2/1/00 - 13 - 25 - 6 - 2", sep="-", header=TRUE)

# find ranks
t(apply(-mydf[-1], 1, rank))

# add to your dates
mydf.rank <- cbind(mydf[1], t(apply(-mydf[-1], 1, rank)))

关于代码

mydf[-1] # removes the first column

-mydf[-1] #using the `-` negates the values -so the rank goes in decreasing order

apply with MARGIN=1 查找跨行的排名

apply with MARGIN=1 finds the ranks across rows

t 转置矩阵以提供您想要的输出

The t transposes the matrix to give the output as you want

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

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