Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
like image 332
staifmis108 Avatar asked Oct 23 '25 04:10

staifmis108


2 Answers

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"
like image 131
Joris C. Avatar answered Oct 25 '25 19:10

Joris C.


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.

like image 26
tmfmnk Avatar answered Oct 25 '25 18:10

tmfmnk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!