rank() function in R returns the ranks of the values in a vector. rank function in R also handles Ties and missing values in several ways.

#### Syntax for rank function in R:

rank(x, na.last = TRUE, ties.method = c(“average”, “first”, “random”, “max”, “min”))

** **

x | numeric, character or logical vector |

na.last | Treatment of NAs. How to Handle NAs |

ties.method | Treatment of Ties. How to Handle Ties |

#### Rank function in R with NAs as last:

x <- c(2,7,1,-17,NA,Inf,35,21) rank(x)

by default NAs are ranked last, so the output will be

[1] 3 4 2 1 8 7 6 5

#### Rank function in R with NAs as First:

NAs are ranked first

x <- c(2,7,1,-17,NA,Inf,35,21) rank(x,na.last = FALSE) #NA FIRST

**output:**

[1] 4 5 3 2 1 8 7 6

**Rank function in R with NAs are removed:**

NAs are neglectled by rank function

x <- c(2,7,1,-17,NA,Inf,35,21) rank(x,na.last = NA) #NA removed

**output:**

[1] 3 4 2 1 7 6 5

**Rank function in R with NAs are ranked as NA:**

NAs are kept and ranked as NAs by rank function

x <- c(2,7,1,-17,NA,Inf,35,21) rank(x,na.last = "keep") #NA is kept with rank NA

**output:**

[1] 3 4 2 1 NA 7 6 5

**Rank function in R with Ties=”Average”:**

Average of the rank is allocated to the elements of vector when ties are encountered

x <- c(2,7,1,-17,NA,Inf,35,21,7) rank(x,na.last = TRUE,ties.method = "first")

**output:**

[1] 3.0 4.5 2.0 1.0 9.0 8.0 7.0 6.0 4.5

**Rank function in R with Ties=”random”:**

x <- c(2,7,1,-17,NA,Inf,35,21,7) rank(x,na.last = TRUE,ties.method = "random")

**output:**

[1] 3 4 2 1 9 8 7 6 5

**Rank function in R with Ties=”max”:**

Maximum value of the rank is allocated to the elements of vector when ties are encountered

x <- c(2,7,1,-17,NA,Inf,35,21,7) rank(x,na.last = TRUE,ties.method = "max")

**output:**

[1] 3 5 2 1 9 8 7 6 5

** **

**Rank function in R with Ties=”min”:**

Minimum value of the rank is allocated to the elements of vector when ties are encountered

x <- c(2,7,1,-17,NA,Inf,35,21,7) rank(x,na.last = TRUE,ties.method = "min")

**output:**

[1] 3 4 2 1 9 8 7 6 4

** **

**Ranking of character vector in R:**

Rank() function can also be used to rank character vector

y<-c("a","h","e","d") rank(y)

**output:**

[1] 1 4 3 2