Home > Net >  create a function that converts roman characters to integers
create a function that converts roman characters to integers

Time:04-23

I want to create a function that reads any roman characters and convert it to integers in R.

I've tried this :

roman_to_integer <- function(roman){
  convert=data.frame(a=c("I","V","X","L","D","M") , b=c(1,5,10,50,500,1000))
  int = 0
  for (i in 1:nrow(convert)){
    value = convert$a[[i]]
    if (i 1 < nchar(roman) & convert$a[[i 1]] > value){
      int = int   value
    } else {
      int = int - value
    } 
 int
 } 

But i have this error :

Error: unexpected symbol in:
"value = convert$row.names[[i]] if i"

How can i improve/fix this ? Thank you !

CodePudding user response:

v <- c("I", "V", "X", "L", "D", "M", "LXXIX")

as.integer(as.roman(v))

# [1]    1    5   10   50  500 1000   79

With as.roman you can do arithmetic operations as well like

as.roman("M") - as.roman("I")

# [1] CMXCIX

CodePudding user response:

Are you aware that this is already implemented in base R?

roman_number <- as.roman("XLII")
roman_number
#> [1] XLII

as.integer(roman_number)
#> [1] 42

You can look at the function implementation with getAnywhere(".roman2numeric").

  • Related