R - extracting value by rank

空扰寡人 提交于 2019-12-31 04:35:05

问题


Suppose I have a data frame that I have ordered according to the Value column and now looks something like this:

Name  Value
A       2
B       2
C       5
D       5
E      10
F      12

I am writing a function where one argument is a rank (e.g. rank=2) and I want the output to be the corresponding name (e.g. C & D). Any ties should be ranked equally.

I would really appreciate any guidance as I've tried multiple ways of accomplishing this and keep getting errors of some sort.


回答1:


We can convert the Value as factor and then convert it into numeric to get equal ranks for same numbers

getRank <- function(rank) {
  df$Name[as.numeric(factor(df$Value)) == rank]
}

getRank(1)
#[1] A B
#Levels: A B C D E F
getRank(2)
#[1] C D
#Levels: A B C D E F
getRank(3)
#[1] E
#Levels: A B C D E F

If we need the output as character we can wrap it in as.character

getRank <- function(rank) {
  as.character(df$Name[as.numeric(factor(df$Value)) == rank])
}



回答2:


You can use match to index against the unique set of values:

get_rank <- function(r) df$Name[match(df$Value, unique(df$Value)) == r]

get_rank(2)
## [1] C D
## Levels: A B C D E F


来源:https://stackoverflow.com/questions/41156385/r-extracting-value-by-rank

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!