Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert ordinal to numbers

Is there a built-in way to convert ordinal numbers to numeric vectors?

ordinal <- c("First", "Third", "Second")
ordinal_to_numeric(ordinal)
#[1] 1 3 2

ordinal2 <- c("1st", "4th", "2nd")
ordinal_to_numeric(ordinal)
#[1] 1 4 2

One could indeed create a dictionary, but this could be cumbersome easily.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Not exactly built-in, but you can use Ritchie Sacramento’s suggestion of the english package. You first make a long string of the ordinal values in words. Then you find the place of your words in these ordered list of ordinal values:

library(english)
ordinal <- c("First", "Third", "Second")
o <- ordinal(1:1000)
match(tolower(ordinal), o)
#> [1] 1 3 2

The second, as Ritchie suggests, is less complicated. I used a slightly different method, but ultimately it does the same thing.

ordinal2 <- c("1st", "4th", "2nd")
as.numeric(stringr::str_extract(ordinal2, "\\d+"))
#> [1] 1 4 2

Created on 2023-01-11 by the reprex package (v2.0.1)

You could even put them together in a single function:

ordinal_to_numeric <- function(x, max_ord=1000){
  if(any(grepl("\\d", x))){
    as.numeric(stringr::str_extract(x, "\\d+"))
  }else{
    require(english, quietly = TRUE)
    o <- ordinal(seq(1,max_ord, by=1))
    match(tolower(x), o)
  }
}
ordinal <- c("First", "Third", "Second")
ordinal_to_numeric(ordinal)
#> [1] 1 3 2

ordinal2 <- c("1st", "4th", "2nd")
ordinal_to_numeric(ordinal2)
#> [1] 1 4 2

Created on 2023-01-11 by the reprex package (v2.0.1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading