Message-ID: <47CBD514.1010003@bitwrit.com.au>
Date: 2008-03-03T10:38:12Z
From: Jim Lemon
Subject: R function to convert a number to text
In-Reply-To: <55511.40027.qm@web35513.mail.mud.yahoo.com>
lin tang wrote:
> hi, Dear R users -
>
> I wonder is there a written R function to convert a number to a text, say convert 1 to "one" , 100 to "one hundred". I know in xls. has such a function BAHTTEXT, does anybody know is there a similar function in R ? Thanks.
>
Hi Lin,
I got bored after the millions, but this should handle the smaller
numbers, and you can always extend it.
digits2text<-function(x,mult="") {
units<-c("one","two","three","four","five",
"six","seven","eight","nine")
teens<-c("ten","eleven","twelve","thirteen","fourteen",
"fifteen","sixteen","seventeen","eighteen","nineteen")
tens<-c("ten","twenty","thirty","forty","fifty",
"sixty","seventy","eighty","ninety")
digits<-rev(as.numeric(strsplit(as.character(x),"")[[1]]))
digilen<-length(digits)
if(digilen == 2 && digits[2] == 1) return(teens[digits[1]+1])
digitext<-units[digits[1]]
if(digilen > 1) digitext<-c(digitext,tens[digits[2]])
if(digilen > 2) digitext<-c(digitext,"hundred",units[digits[3]])
if(digilen > 3) digitext<-
c(digitext,digits2text(floor(x/1000),"thousand"))
if(digilen > 6) digitext<-
c(digitext,digits2text(floor(x/1000000),"million"))
return(paste(c(rev(digitext),mult),sep="",collapse=" "))
}
Jim