[R] Rounding and printing

David Winsemius dwinsemius at comcast.net
Thu Oct 29 18:05:28 CET 2009


On Oct 29, 2009, at 12:29 PM, Alan Cohen wrote:

> Hello,
>
> I am trying to print a table with numbers all rounded to the same  
> number of digits (one after the decimal), but R seems to want to not  
> print ".0" for integers.  I can go in and fix it one number at a  
> time, but I'd like to understand the principle.  Here's an example  
> of the code.  The problem is the 13th element, 21 or 21.0:
>> nvb_deaths <- round(ss[,10]/100,digits=1)
>> nvb_deaths
> [1] 56.5  1.6  0.2  3.9  0.1  2.2  0.2  2.6  1.5  4.1  1.1  6.1 21.0

?sprintf  # fmt = "%1.1f"

  nvb_dths <- paste(sprintf("%1.1f",  
nvb_deaths)," (",round(100*nvb_deaths/ 
nvb_deaths[1],digits=1),"%)",sep="")

 > nvb_dths
  [1] "56.5 (100%)"  "1.6 (2.8%)"   "0.2 (0.4%)"   "3.9 (6.9%)"   "0.1  
(0.2%)"   "2.2 (3.9%)"   "0.2 (0.4%)"
  [8] "2.6 (4.6%)"   "1.5 (2.7%)"   "4.1 (7.3%)"   "1.1 (1.9%)"   "6.1  
(10.8%)"  "21.0 (37.2%)"


>> nvb_dths <- paste(nvb_deaths," (",round(100*nvb_deaths/ 
>> nvb_deaths[1],digits=1),"%)",sep="")
>> nvb_dths
> [1] "56.5 (100%)" "1.6 (2.8%)"  "0.2 (0.4%)"  "3.9 (6.9%)"  "0.1  
> (0.2%)"  "2.2 (3.9%)"
> [7] "0.2 (0.4%)"  "2.6 (4.6%)"  "1.5 (2.7%)"  "4.1 (7.3%)"  "1.1  
> (1.9%)"  "6.1 (10.8%)"
> [13] "21 (37.2%)"
>> print(nvb_deaths,digits=1)
> [1] 56.5  1.6  0.2  3.9  0.1  2.2  0.2  2.6  1.5  4.1  1.1  6.1 21.0
>> paste(print(nvb_deaths,digits=1)," (",round(100*nvb_deaths/ 
>> nvb_deaths[1],digits=1),"%)",sep="")
> [1] 56.5  1.6  0.2  3.9  0.1  2.2  0.2  2.6  1.5  4.1  1.1  6.1 21.0
> [1] "56.5 (100%)" "1.6 (2.8%)"  "0.2 (0.4%)"  "3.9 (6.9%)"  "0.1  
> (0.2%)"  "2.2 (3.9%)"
> [7] "0.2 (0.4%)"  "2.6 (4.6%)"  "1.5 (2.7%)"  "4.1 (7.3%)"  "1.1  
> (1.9%)"  "6.1 (10.8%)"
> [13] "21 (37.2%)"
>
> I'm running R v2.8.1 on Windows.  Any help is much appreciated.
>
> Cheers,
> Alan Cohen
>
> ______________________________________________
> 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
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list