# Re: [R] R function to convert a number to text

From: Alberto Monteiro <albmont_at_centroin.com.br>
Date: Mon, 03 Mar 2008 10:17:26 -0200

Jim Lemon wrote:
>
> 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=" "))
> }
>
Be careful, the function does not handle "empty" fields:

> digits2text(10^6 + 10)

[1] "one million one thousand hundred thousand hundred ten "

Alberto Monteiro (today I am purely destructive)

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Mon 03 Mar 2008 - 12:20:13 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 04 Mar 2008 - 09:30:18 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.