如何用R rank()函数创建一个新的ties.method? [英] How I can create a new ties.method with the R rank() function?

查看:188
本文介绍了如何用R rank()函数创建一个新的ties.method?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照人口和日期排序这个数据框,所以我使用 order() rank()函数:

 > df<  -  data.frame(idgeoville = c(5,8,4,3,4,5,8,8),
date = c(rep(1950,4))rep(2000,4) ),
population = c(500,450,350,350,650,500,500,450))
> df
idgeoville日期人口
1 5 1950 500
2 8 1950 450
3 4 1950 350
4 3 1950 350
5 4 2000 650
6 5 2000 500
7 8 2000 500
8 8 2000 450

使用 ties.method =first我没有问题,最后我生产这个数据框:

  idgeoville日期人口排名
1 5 1950 500 1
2 8 1950 450 2
3 4 1950 350 3
4 3 1950 350 4
5 4 2000 650 1
6 5 2000 500 2
7 8 2000 500 3
8 8 2000 450 4

但实际上,我想要一个具有相同排名的等级排名的数据框,如下所示:

  idgeov ille日期人口等级
1 5 1950 500 1
2 8 1950 450 2
3 4 1950 350 3
4 3 1950 350 3
5 4 2000 650 1
6 5 2000 500 2
7 8 2000 500 2
8 8 2000 450 3

如何用R解决这个问题?使用自定义 ties.method()或另一个R技巧?

解决方案

我相信没有选择做排名;这里是一个自定义的功能,可以做你想要的,但如果您的数据很大,可能会太慢:

  -function(d){
j< -unique(rev(sort(d)));
return(sapply(d,function(dd)which(dd == j)));
}


I'm trying to order this dataframe by population and date, so I'm using the order() and rank() functions:

> df <- data.frame(idgeoville = c(5, 8, 4, 3, 4, 5, 8, 8),
                   date       = c(rep(1950, 4), rep(2000, 4)),
                   population = c(500, 450, 350, 350, 650, 500, 500, 450))
> df
   idgeoville date    population
1  5          1950     500
2  8          1950     450
3  4          1950     350
4  3          1950     350
5  4          2000     650
6  5          2000     500
7  8          2000     500
8  8          2000     450

With ties.method = "first" I have no problem, finally I'm producing this dataframe:

   idgeoville date    population  rank
1  5          1950     500        1
2  8          1950     450        2
3  4          1950     350        3
4  3          1950     350        4
5  4          2000     650        1
6  5          2000     500        2
7  8          2000     500        3
8  8          2000     450        4

But in fact, I want a dataframe with equal ranking for equal population rank, like this:

   idgeoville date    population  rank
1  5          1950     500        1
2  8          1950     450        2
3  4          1950     350        3
4  3          1950     350        3
5  4          2000     650        1
6  5          2000     500        2
7  8          2000     500        2
8  8          2000     450        3

How can I resolve this problem with R? With a custom ties.method() or another R tricks?

解决方案

I believe there is no option to do it with rank; here is a custom function that will do what you want, but it may be too slow if your data is huge:

Rank<-function(d) {
    j<-unique(rev(sort(d)));
    return(sapply(d,function(dd) which(dd==j)));
}

这篇关于如何用R rank()函数创建一个新的ties.method?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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