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