Search code examples
rroman-numerals

Convert roman numerals to numbers in R


In R, there is a great function as.roman in the very base setup:

as.roman(79)
# [1] LXXIX

Is there an inverse function that would convert roman numerals to numbers?

I know I can write it myself but I'd prefer to use already prepared or preferably standard library functions.


Solution

  • as.roman() returns an object of class roman, so R recognizes it as such. You can directly turn it back into an Arabic numeral with as.numeric(). If you have a string that meets the criteria such that it could be a valid roman numeral, you can coerce it to a class roman object with as.roman(), and then coerce it into an Arabic numeral by composing the coercion functions. Consider:

    > as.roman(79)
    [1] LXXIX
    > x <- as.roman(79)
    > x
    [1] LXXIX
    > str(x)
    Class 'roman'  int 79
    > as.roman("LXXIX")
    [1] LXXIX
    > as.numeric(as.roman("LXXIX"))
    [1] 79