我已经创建了这个函数,可以将任何9或更少的内容转换为单词,并且还可以通过插入逗号来格式化大数字:
library(english); library(stringr)
reportNumber <- function (number) {
ifelse(number > 9, str_trim(format(number, big.mark= ",", scientific = F)), as.character(english(number)))
}
该功能的工作原理如下:
reportNumber(c(0, 9, 10, 100, 1000, 10000))
# [1] "zero" "nine" "10" "100" "1,000" "10,000"
但如果数字有小数点,则函数错误:
reportNumber(c(0.1, 9.1, 10.1, 100.1, 1000.1, 10000.1))
我需要让函数测试数字是否有小数点,如果为true,则只打印未格式化的数字。所以输出应该只是:
c(0.1, 9.1, 10.1, 100.1, 1000.1, 10000.1)
# [1] 0.1 9.1 10.1 100.1 1000.1 10000.1
答案 0 :(得分:1)
您的问题基本上归结为检查数字是否为整数,在SO上已经解决了before。你可以试试:
reportNumber <- function (number) {
ifelse(number %% 1 != 0, as.character(number),
ifelse(number > 9,
str_trim(format(number, big.mark= ",", scientific = F)),
as.character(english(number))))
}
reportNumber(c(0, 9, 10, 100, 1000, 10000))
# [1] "zero" "nine" "10" "100" "1,000" "10,000"
reportNumber(c(0.1, 9.1, 10.1, 100.1, 1000.1, 10000.1))
# [1] "0.1" "9.1" "10.1" "100.1" "1000.1" "10000.1"