Simd
Simd

Reputation: 21343

Why does print(x, digits=n) behave differently in different places?

Take these two examples:

print(687.7, digits = 3)
688

and also

> print(matrix(1000*runif(60),nrow=5),digits = 3)
     [,1]  [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]  210  27.5  702  628  180  981  562  614  256   998   202 721.5
[2,]  818 113.0  138  249  460  680  883  355  333   200   765  40.5
[3,]  978 134.0  128  175   29  312  272  321  293   478   909 635.7
[4,]  201 687.7  270  334  337  660  133  797  237   498   934 903.0
[5,]  432 694.0  492  868  415  199  791  831  819   999   900 924.9

Why does 687.7 (for example) appear in the second output but not the first?

Upvotes: 1

Views: 37

Answers (1)

Tensibai
Tensibai

Reputation: 15784

To answer the question in the title: it doesn't behave differently by context or where it is called, the behavior difference is due to what data you give as input.

From print.default doc on digits:

a non-null value for digits specifies the minimum number of significant digits to be printed in values.".

That's why it takes the decimals for 27.5 and 40.5 to have 3 significant digits, and once done, it switch to printing the decimal for all values of the same column.

Exemple with simple vector to illustrate:

> z<-c(1,2,3.0)
> print(z,digits=3)
[1] 1 2 3
> z<-c(1,2,3.01)
> print(z,digits=3)
[1] 1.00 2.00 3.01

First exemple the decimal is non significant, not printed, the second is and switch everyone to two decimal printing

Upvotes: 2

Related Questions