Skip to content
Prev 67865 / 398502 Next

How to create a vector with "one", "two", "three", ...?

Dear Frank,

This was an interesting exercise. Here's a solution:

numbers2words <- function(x){
    helper <- function(x){
        digits <- rev(strsplit(as.character(x), "")[[1]])
        nDigits <- length(digits)
        if (nDigits == 1) as.vector(ones[digits])
        else if (nDigits == 2)
            if (x <= 19) as.vector(teens[digits[1]])
                else trim(paste(tens[digits[2]],
Recall(as.numeric(digits[1]))))
        else if (nDigits == 3) trim(paste(ones[digits[3]], "hundred", 
            Recall(makeNumber(digits[2:1]))))
        else {
            nSuffix <- ((nDigits + 2) %/% 3) - 1
            if (nSuffix > length(suffixes)) stop(paste(x, "is too large!"))
            trim(paste(Recall(makeNumber(digits[
                nDigits:(3*nSuffix + 1)])),
                suffixes[nSuffix],  
                Recall(makeNumber(digits[(3*nSuffix):1]))))
            }
        }
    trim <- function(text){
        gsub("^\ ", "", gsub("\ *$", "", text))
        }      
    makeNumber <- function(...) as.numeric(paste(..., collapse=""))
    opts <- options(scipen=100)
    on.exit(options(opts))
    ones <- c("", "one", "two", "three", "four", "five", "six", "seven", 
        "eight", "nine")
    names(ones) <- 0:9 
    teens <- c("ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",

        "sixteen", " seventeen", "eighteen", "nineteen")
    names(teens) <- 0:9
    tens <- c("twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", 
        "ninety")
    names(tens) <- 2:9 
    x <- round(x)
    suffixes <- c("thousand", "million", "billion", "trillion")
    if (length(x) > 1) return(sapply(x, helper))
    helper(x)
    }

For example:
[1] "fifty six trillion seven hundred thirty four billion two hundred
million four thousand three hundred fifty"
[1] "five billion six hundred seventy three million four hundred twenty
thousand"
[2] "six hundred four"
[1] "twenty one"   "twenty two"   "twenty three" "twenty four"  "twenty
five" 
 [6] "twenty six"   "twenty seven" "twenty eight" "twenty nine"  "thirty"
Note that if you want, you could go beyond trillions by adding to suffixes.

I hope that this does what you want,
 John

--------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario
Canada L8S 4M4
905-525-9140x23604
http://socserv.mcmaster.ca/jfox 
--------------------------------