Is there a fast way to convert Roman numerals in the string to Arabic in R?

Viewed 349

I'm trying to convert the Roman numerals in a string to Arabic.

I tried using stringr::str_sub to select the corresponding characters and use as.numeric(as.roman()) to convert, but it's messier than I thought.

A <- c("Case I", "Big Case II", "Not a Case", "This is Case IV")

I expect the output to be:

"Case 1" "Big Case 2" "Not a Case" "This is Case 4"
2 Answers

One possibility could be:

sapply(sapply(A, function(x) strsplit(x, " ", fixed = TRUE), USE.NAMES = FALSE), 
       function(x) paste(x[1], as.numeric(as.roman(x[2])), collapse = " "))

[1] "Case 1" "Case 2" "Case 3" "Case 4"

Here it splits the original string on a whitespace, converts the second element to arabic number and then pastes the two elements back together.

You can directly pass a function to the replacement argument of str_replace:

library(stringr)

str_replace(A, "[IVX]+$", function(x) as.numeric(as.roman(x)))
#> [1] "Case 1"         "Big Case 2"     "Not a Case"     "This is Case 4"
Related