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

From: Jim Lemon <jim_at_bitwrit.com.au>
Date: Tue, 04 Mar 2008 20:11:12 +1100

Alberto Monteiro wrote:
> ...
> Be careful, the function does not handle "empty" fields:

Okay, Alberto, you asked for it!

digits2text<-function(x,illion=0) {
  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")
  illions<-c("thousand","million","billion","trillion","quadrillion")   digits<-rev(as.numeric(strsplit(as.character(x),"")[[1]]))   if(is.numeric(x)) {
   cat("illion =",illion,"\n")
   digilen<-length(digits)
   cat("digilen =",digilen,"\n")
   if(digilen == 1) digitext<-units[digits[1]]    if(digilen > 1) {
    if(digits[2] == 1) digitext<-c(teens[digits[1]+1])     else digitext<-c(tens[digits[2]],units[digits[1]])    }
   if(digilen > 2 && digits[3] > 0)
    digitext<-c(units[digits[3]],"hundred",digitext)    if(digilen > 3)
    digitext<-c(digits2text(x%/%1000,illion+1),digitext)    cat("digitext =",digitext,"\n")
   print(digits[1:3])
   if(sum(digits[1:3],na.rm=TRUE) > 0)
    return(paste(c(digitext,illions[illion]),sep="",collapse=" "))    else
    return(paste(digitext,sep="",collapse=" "))   }
  else cat("That wasn't a number, Alberto!\n") }

Jim



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 Tue 04 Mar 2008 - 09:24:56 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 - 10: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.

list of date sections of archive