[R] Converting numbers into words

Gabor Grothendieck ggrothendieck at gmail.com
Sun Dec 5 18:13:10 CET 2010


On Sun, Dec 5, 2010 at 11:50 AM, Thomas Levine <thomas.levine at gmail.com> wrote:
> Example data
>
> desk=data.frame(
> deskchoice=c('mid','mid','left','bookdrop','mid','bookdrop')
> )
>
> --
>
> I like doing stuff like the line below, especially when I'm using Sweave.
>
> print(paste('Within the observation period,',nrow(desk),
> 'patrons approached the circulation desk.'))
>
>
> --
>
> But what if I want to put it at the beginning of a sentence?
>
> print(sum(desk$deskchoice=='bookdrop'),'persons',
> 'used the book drop. Everyone else interacted with a staff member.')
>
> Is there a pretty way to change the result of
> sum(desk$deskchoice=='bookdrop')
> from "2" to "Two"?
>
> --
>
> And what if the number is one?
>
> print(sum(desk$deskchoice=='bookdrop'),
>  c('person','persons')[as.numeric(sum(desk$deskchoice=='bookdrop')!=1)+1],
> 'used the book drop. Everyone else interacted with a staff member.')
>
> Is there a prettier way of choosing between "person" and "persons"?

Using John Fox's numbers2words found here:

   http://tolstoy.newcastle.edu.au/R/help/05/04/2715.html

and capwords found in the examples section of ?toupper try this:

   n <- sum(desk$deskchoice == "bookdrop")
   paste(capwords(numbers2words(n)), if (n == 1) "person" else
"people", "used the book drop...")

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list