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

时间:2019-02-26 09:18:04

标签: r type-conversion sapply

如帖子Convert roman numerals to numbers in R中所述,有一个将数字转换为罗马数字的功能。但是,当尝试通过过滤非数字符号进行转换时

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 还是符号表示形式(例如编码)出现错误?

1 个答案:

答案 0 :(得分:1)

嗨,

我认为您必须添加一个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中输出的缩短将默认情况下将罗马类转换回其数值。因此,首先将所有输出转换为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"