[R] round and trailing zero

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Mon Jul 29 16:22:58 CEST 2024


On 2024-07-29 10:06 a.m., Göran Broström wrote:
> I have a "result":
> 
>   > hazards
>           (60, 70]    (70, 80]    (80, 90]   (90, 100]
> [1,] 0.046612937 0.115643783 0.273613266 0.450127975
> 
> Two issues: (i) Too many decimals, and (ii) it seems to be an 1x4
> matrix, I only need the first row. (i):
> 
>   > haz <- round(hazards, 3)
>   > haz
>        (60, 70] (70, 80] (80, 90] (90, 100]
> [1,]    0.047    0.116    0.274      0.45
> 
> As expected, the fourth element lost a trailing zero. I'll deal with
> that, but first (ii):
> 
>   > haz[1, ]
>    (60, 70]  (70, 80]  (80, 90] (90, 100]
>       0.047     0.116     0.274     0.450
> 
> And the trailing zero is mysteriously recovered!
> 
> Is there some general rule governing this behaviour?

R uses the same format for every element in each column when printing a 
matrix or dataframe, and for every element in a vector.

Your first example had only one element per column.  If you had printed 
t(haz) you'd get numbers displayed like the second version, where 
haz[1,] converts that row to a vector.

Duncan Murdoch



More information about the R-help mailing list