[R] R function to convert a number to text

Jim Lemon jim at bitwrit.com.au
Tue Mar 4 10:11:12 CET 2008


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



More information about the R-help mailing list