[R] Help with format()

David Winsemius dwinsemius at comcast.net
Fri Aug 19 16:51:58 CEST 2011


On Aug 19, 2011, at 10:23 AM, Michael Karol wrote:

> R Users:
>
>  Can anyone please help me with the following:
>  I'm unclear as to how to get format to do what I want.
>  I've tried the following and get unexpected results.
>
> Input.....
> val<-321.6
>
> format(val, digits=1)
> format(val, digits=2)
> format(val, digits=3)
> format(val, digits=4)
> format(val, digits=5)
>
> Output....
>
> [1] "322"
> [1] "322"
> [1] "322"
> [1] "321.6"
> [1] "321.6"
>
> Whereas I would expect to get...
>
> [1] "300"
> [1] "320"
> [1] "322"
> [1] "321.6"
> [1] "321.60"
>
> since "digits" is defined as the number of "significant digits".   
> The number 321.6 shown to 1 significant digit should be 300., not  
> 322 which is 3 significant digits!  Likewise for the other cases.
>
> Can anyone explain what format() is doing?

As you are observing the "significance" test only starts to kick in to  
the right of the decimal, but it does not "add" or "extend"  
significance to numbers that don't have the specified extent. (I agree  
the help page is not clear on these points.) If you want to force a  
particular size then you would want sprintf or formatC (as the help  
page for format does link to.)

>
>
> Regards,
> Michael
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list