9

For the purpose of styling data visualizations, I'd like to be able to display an integer using words (e.g.

"Two thousand and seventeen"

) rather than digits (e.g. 2017).

As an example of what I'm looking for, here's a quick function that works for a small, scalar integer:

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)
Hack-R
  • 22,422
  • 14
  • 75
  • 131
bschneidr
  • 6,014
  • 1
  • 37
  • 52
  • 1
    I edited out one sentence of your question because it's against SO rules to ask for library recommendations. Anyway, have you seen this one (goes in the other direction but is easily reversed) https://stackoverflow.com/questions/18332463/convert-written-number-to-number-in-r ? – Hack-R Oct 09 '17 at 17:41
  • 1
    Well I already gave you the solution linked above and another one in my answer below, but vague or specific it's just against the rules to ask for library recommendations. Not a big deal, it's easily edited out of the question and people can still answer with libraries. Rules are just rules, you know? – Hack-R Oct 09 '17 at 17:46

2 Answers2

28

Option 1:

Use the as.english function from the 'english' package:

library(english)

as.english(2017)


Option 2:

Use the replace_number function from the 'qdap' package.

library(qdap)

replace_number(2017)


Option 3:

Use the numbers_to_words function from the 'xfun' package.

library(xfun)

numbers_to_words(2017)
bschneidr
  • 6,014
  • 1
  • 37
  • 52
5

Asides from the function I linked in the comments, here's another solution from a GitHub gist:

source("https://gist.githubusercontent.com/hack-r/22104543e2151519c41a8f0ce042b31c/raw/01731f3176b4ee471785639533d38eda4790ab77/numbers2words.r")

numbers2words(0)

[1] "zero"

numbers2words(5)

[1] "five"

numbers2words(50000)

[1] "fifty thousand"

numbers2words(50000000000000)

[1] "fifty trillion"

Hack-R
  • 22,422
  • 14
  • 75
  • 131