将整数转换为文字

9
为了美化数据可视化,我希望能够用文字(例如“二千零十七”)而不是数字(例如2017)来显示整数。以下是一个适用于小型标量整数的快速函数示例:
int_to_words <- function(x) {

                   index <- as.integer(x) + 1
                   words <- c('zero', 'one', 'two', 'three', 'four',
                              'five', 'six', 'seven', 'eight', 'nine',
                              'ten')
                   words[index]
}


int_to_words(5)

1
我编辑了你的问题中的一句话,因为向SO(Stack Overflow)询问库推荐是违反规则的。不管怎样,你看过这个吗(这个是反过来的,但很容易改成正着的) https://dev59.com/dmMl5IYBdhLWcg3wgnWl? - Hack-R
1
我已经在上面的链接中给出了解决方案,并在下面的回答中提供了另一个解决方案,但是无论是模糊还是具体,都违反了要求询问库推荐。这不是什么大问题,可以轻松地从问题中删除并且人们仍然可以使用库来回答。规则就是规则,你知道吗? - Hack-R
2个回答

29

选项1:

使用英语包中的as.english函数:

library(english)

as.english(2017)


选项2:

使用“qdap”包中的replace_number函数。

library(qdap)

replace_number(2017)


选项 3:

使用“xfun”包中的numbers_to_words函数。

library(xfun)

numbers_to_words(2017)

5
除了我在评论中提到的函数,这里有另外一个来自GitHub gist的解决方案:
source("https://gist.githubusercontent.com/hack-r/22104543e2151519c41a8f0ce042b31c/raw/01731f3176b4ee471785639533d38eda4790ab77/numbers2words.r")

numbers2words(0)

[1] "零"
numbers2words(5)

[1] "five"

numbers2words(50000)

[1] "五万"

numbers2words(50000000000000)

[1] "五十万亿"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接