Stopping a large number of zeros being printed (not scientific notation)
Asked Answered
M

2

11

What I'm trying to achieve is to have all printed numbers display at maximum 7 digits. Here are examples of what I want printed:

0.000000 (versus the actual number which is 0.000000000029481.....)

0.299180 (versus the actual number which is 0.299180291884922.....)

I've had success with the latter types of numbers by using options(scipen=99999) and options(digits=6). However, the former example will always print a huge number of zeros followed by five non-zero digits. How do I stop this from occurring and achieve my desired result? I also do not want scientific notation.

I want this to apply to ALL printed numbers in EVERY context. For example if I have some matrix, call it A, and I print this matrix, I want every element to just be 6-7 digits. I want this to be automatic for every print in every context; just like using options(digits=6) and options(scipen=99999) makes it automatic for every context.

Millican answered 29/12, 2012 at 9:27 Comment(2)
What if you have a large number, for example 123456789.87654321. How can you print it using at most 7 digits if you are not going to use scientific notation?!Invercargill
@Invercargill Good point. Maybe I would like these very large numbers to use scientific notation (or extend beyond 6 digits). But if there only exists a solution that truncates EVERY dumber do 6-7 digits; that's fine, since I never work with large numbers that I need to print in the R console.Millican
C
12

You can define a new print method for the type you wish to print. For example, if all your numbers are doubles, you can create

print.double=function(x){sprintf("%.6f", x)}

Now, when you print a double (or a vector of doubles), the function print.double() will be called instead of print.default().

You may have to create similar functions print.integer(), print.complex(), etc., depending on the types you need to print.

To return to the default print method, simply delete the function print.double().

Caraway answered 5/1, 2013 at 14:9 Comment(0)
T
3

Are all your numbers < 1? You could try a simple sprintf( "%.6f", x ). Otherwise you could try wrapping things to sprintf based on the number of digits; check ?sprintf for other details.

Turnedon answered 29/12, 2012 at 11:23 Comment(1)
I want this to automatically apply to every single number print; a solution that's similar to options(digits=6) in that it just applies to every object in every context and I only need to set it once. Not everything is < 1, but everything that I need to print interactively is < 100.Millican

© 2022 - 2024 — McMap. All rights reserved.