[R] How to avoid rounding of matrix elements?

Marc Schwartz MSchwartz at MedAnalytics.com
Fri Jan 7 02:52:11 CET 2005


On Thu, 2005-01-06 at 18:57 -0500, Ulas Karaoz wrote:
> Hi all R-users,
> If I have a matrix with numeric elements as follows, the values are 
> rounded when I try to refer to a specifici element using [], the
> value 
> is rounded.
> The same thing happens if the matrix is read from a file, the values
> are 
> stored to the correct precision but then when I try to refer to a 
> specific element (such as using [], it is rounded.
> 
> How do I avoid this rounding?
>  >mdat<-matrix(c
> (0.0187972950,0.4446208550,1.0000000000,0.0003204380,0.0105002420,1.1087556380,0.0742164230,0.0362898240), 
> nrow = 2, ncol=4)
>  > mdat
>            [,1]        [,2]       [,3]       [,4]
> [1,] 0.01879729 1.000000000 0.01050024 0.07421642
> [2,] 0.44462085 0.000320438 1.10875564 0.03628982
> 
> Thanks.

When you display the matrix, you are using a print method to do so. In
this case print.matrix() is being used. If you review the help for the
function (or ?print.default), you will see that there is an argument
called 'digits' which, if not explicitly defined, is set to 
options("digits"), which by default is 7.

Note importantly, that this has _nothing_ to do with the fashion in
which the data is being stored internally, which is by default a
'double' precision float. This only affects how the data is displayed.

The digits option, when printing a multi-element structure, is the
_minimum_ number of significant digits that will be printed.

If you want additional control over the number of decimal places that is
printed, you can do this in several ways:

# Explicitly use the print function
> print(mdat, digits = 9)
            [,1]        [,2]        [,3]        [,4]
[1,] 0.018797295 1.000000000 0.010500242 0.074216423
[2,] 0.444620855 0.000320438 1.108755638 0.036289824

# Increase 'digits' globally
> options(digits = 9)
> mdat
            [,1]        [,2]        [,3]        [,4]
[1,] 0.018797295 1.000000000 0.010500242 0.074216423
[2,] 0.444620855 0.000320438 1.108755638 0.036289824


# Use a format family function
> formatC(mdat, format = "f", digits = 12)
     [,1]             [,2]             [,3]            
[1,] "0.018797295000" "1.000000000000" "0.010500242000"
[2,] "0.444620855000" "0.000320438000" "1.108755638000"
     [,4]            
[1,] "0.074216423000"
[2,] "0.036289824000"


See:

?print.default
?options
?formatC
?format
?sprintf

for more information.

HTH,

Marc Schwartz




More information about the R-help mailing list