Skip to content

OK this is fun: 1st, 2nd, 3rd, 4th, … in R

January 16, 2013

Here’s a fun function:

int_to_ranking <- function(i){
  
  whereinf <- is.infinite(i)
  wherena <- is.na(i)
  whereneg <- sign(i) == -1L
  i <- suppressWarnings(as.integer(i))
  if(any(is.na(i) & (!whereinf) & (!wherena))) stop('could not convert some inputs to integer')
  
  last_digit <- as.numeric(substring(i, nchar(i)))
  ending <- sapply(last_digit + 1, switch, 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th')
  second_last_digit <- as.numeric(substring(i, nchar(i) - 1, nchar(i) - 1))
  ending[second_last_digit == 1L] <- 'th'
  out <- paste(i, ending, sep = '')
  
  out[whereinf] <- 'infinitieth'
  out[whereinf & whereneg] <- '-infinitieth'
  out[wherena] <- 'missingith'
  
  return(out)
}

For example:


x <- c(2, -56.453, NA, 0, 100, 1/0, 1, 10001, 33, 65, -2532.0346/0, 312)
int_to_ranking(x)
## [1] "2nd"          "-56th"        "missingith"   "0th"          "100th"        "infinitieth"  "1st"         
## [8] "10001st"      "33rd"         "65th"         "-infinitieth" "312th"       
int_to_ranking(1:25)
## [1] "1st"  "2nd"  "3rd"  "4th"  "5th"  "6th"  "7th"  "8th"  "9th"  "10th" "11th" "12th" "13th" "14th" "15th" "16th"
## [17] "17th" "18th" "19th" "20th" "21st" "22nd" "23rd" "24th" "25th"

I may have missed some special cases.

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: