R - 按等级提取价值 [英] R - extracting value by rank

查看:71
本文介绍了R - 按等级提取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数据框,我已经根据Value列进行了排序,现在看起来像这样:

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

我正在写一个函数,其中一个参数是一个等级(例如rank = 2),我希望输出是相应的名称(例如C& D) 。任何关系都应该排名相同。

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.

推荐答案

我们可以将 Value 转换为 factor ,然后将其转换为数字,以获得相同数字的相同等级。

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

如果我们需要输出为字符,我们可以用 as.character

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])
}

这篇关于R - 按等级提取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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