nbsullivan742
nbsullivan742

Reputation: 33

R: rank objects in a vector - don't skip an integer after a tie

This seems like a simple question but for the life of me I can't figure it out.

Given the following vector:

a <- c(1, 6, 6, 11)

How do I output a corresponding vector of value ranks like the one below

1 2 2 3

In other words, is there a way to use the rank() or something similar that identifies ties, but doesn't skip an integer on the subsequent value rank.

Upvotes: 0

Views: 108

Answers (2)

akrun
akrun

Reputation: 887088

We can use dense_rank

library(dplyr)
dense_rank(a)
#[1] 1 2 2 3

Or with frank

library(data.table)
frank(a, ties.method = 'dense')
#[1] 1 2 2 3

Or in base R with match

match(a, unique(a))
#[1] 1 2 2 3

Upvotes: 1

Duck
Duck

Reputation: 39595

You can also treat the vector a as factor and the transform to numeric like this:

#Code
as.numeric(as.factor(a))

Output:

[1] 1 2 2 3

Upvotes: 1

Related Questions