8

How can I specify, using one command, the number of digits displayed during an entire R session? That is to say, how can I get the value 0 to always display as 0.0? I've tried the command options(digits=1), but 0 still displays as 0 and not 0.0. I'm really trying to avoid wrapping each command in something like print(ifelse(x==0,"0.0",x)).

It would also be nice if the solution to this problem made, say, 5 show up as 5.0.

1
  • This falls under "you could, but should you?" There's no reason other than some personal aesthetic to do this, and it may mislead you when dealing with integers vs. floats. Remember that what's displayed is not related to the precision with which the numbers are stored, and further that it's trivial to force this sort of formatting when sprintf-ing to a file. Commented Nov 28, 2012 at 1:24

2 Answers 2

6

I'm not sure if there is an options for trailing 0's. One possibility would be to have your own print.numeric and print.integer functions.

print.integer <- print.numeric <- function(..., digs=1)   {
    print(format(as.numeric(...), nsmall=digs), quote=F)
}

It still requires print, but is neater

> print(-1:5)
[1] -1.0  0.0  1.0  2.0  3.0  4.0  5.0


Alternatively, you can use the nsmall argument in format directly.

mat <- matrix(as.numeric(rep(0:3, 5)), ncol=4)
print(format(mat, nsmall=2), quote=F)
0

You can try my package formattable.

> # devtools::install_github("renkun-ken/formattable")
> library(formattable)
> n <- formattable(0, format = "f", digits = 1)
> n
[1] 0.0

n is a formattable, numeric vector that preserves its formatting in arithmetic calculations.

> n+5
[1] 5.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.