Created
September 1, 2015 21:48
-
-
Save npjc/898d8d81bee57b81c14c to your computer and use it in GitHub Desktop.
numbers2words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# John Fox's numbers2words found here: | |
# http://tolstoy.newcastle.edu.au/R/help/05/04/2715.html | |
numbers2words <- function(x){ | |
# helper | |
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 | |
trim <- function(text){ | |
gsub("^\ ", "", gsub("\ *$", "", text)) | |
} | |
# maekNum | |
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment