[R] Rounding and printing

Alan Cohen CohenA at smh.toronto.on.ca
Thu Oct 29 17:29:42 CET 2009


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
>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




More information about the R-help mailing list