在R中将数字转换为罗马数字

Convert numbers to roman numerals in sapply in R

正如在post Convert roman numerals to numbers in R中提到的,有一个函数可以将数字转换为罗马数字。但是,当尝试在 sapply 过滤非数字符号时进行转换

sequence.to_roman<-c(1,2,"V1","df",3)
sapply(sequence.to_roman, function(x) if(grepl("^[1-9]\d*$",x)) as.roman(x) else "Some symbols")

数字保持不变。尽管它以元素方式完美运行。是函数 as.roman 还是符号表示(例如编码)行为错误?

嗨,

我想你必须像这样添加一个 as.character:

    sapply(sequence.to_roman, function(x) as.character(if(grepl("^[1-9]\d*$",x)) as.roman(x) else "Some symbols"))
> sapply(sequence.to_roman, function(x) as.character(if(grepl("^[1-9]\d*$",x)) as.roman(x) else "Some symbols"))
             1              2             V1             df              3 
           "I"           "II" "Some symbols" "Some symbols"          "III" 

看起来缩短 sapply 中的输出会默认将 class 罗马值转换回其数值。因此,首先将所有输出转换为 char 可以防止这种情况。

尝试:

lapply(sequence.to_roman, function(x) if(grepl("^[1-9]\d*$",x)) as.roman(x) else "Some symbols")
> lapply(sequence.to_roman, function(x) if(grepl("^[1-9]\d*$",x)) as.roman(x) else "Some symbols")
[[1]]
[1] I

[[2]]
[1] II

[[3]]
[1] "Some symbols"

[[4]]
[1] "Some symbols"

[[5]]
[1] III

这就是我们想要的,但是:

unlist(lapply(sequence.to_roman, function(x) if(grepl("^[1-9]\d*$",x)) as.roman(x) else "Some symbols"))
> unlist(lapply(sequence.to_roman, function(x) if(grepl("^[1-9]\d*$",x)) as.roman(x) else "Some symbols"))
[1] "1"            "2"            "Some symbols" "Some symbols" "3"   

还给出了重新编码形式。

对于导致问题的原因可能更明显的描述:

> as.roman("3")
[1] III
> as.character(as.roman("3"))
[1] "III"
> c(as.roman("3"), "test")
[1] "3"    "test"
> c(as.character(as.roman("3")), "test")
[1] "III"  "test"