nthobservation
nthobservation

Reputation: 119

What explains the results of rank() function on a negative numerical vector?

x1 <- c(3, 1, 4, 15, 92)
rank(x1)
[1] 2 1 3 4 5

-x1
[1]  -3  -1  -4 -15 -92

rank(-x1)
[1] 4 5 3 2 1

Why doesn't rank(-x1) give 5,4,3,1,2 as the result?

Upvotes: 1

Views: 254

Answers (2)

deschen
deschen

Reputation: 10996

Because -92 is the smallest number and so on. -1 is the largest one, hence rank 5.

Upvotes: 1

akrun
akrun

Reputation: 887251

The function would be order instead of rank

order(-x1)
#[1] 5 4 3 1 2

We can also get to the same output as rank if we do order twice

order(order(-x1))
#[1] 4 5 3 2 1

Also, the rank output depends on the ties.method and if there are any duplicates. It can take a value of "average", "first", "last", "random", "max", "min".

Upvotes: 1

Related Questions