Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting All decimal places in R

Tags:

r

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.

like image 923
Chernoff Avatar asked Nov 27 '12 22:11

Chernoff


People also ask

How do you round to 3 decimal places in R?

You can use the following functions to round numbers in R: round(x, digits = 0): Rounds values to specified number of decimal places. signif(x, digits = 6): Rounds values to specified number of significant digits. ceiling(x): Rounds values up to nearest integer.


1 Answers

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)
like image 130
Ricardo Saporta Avatar answered Sep 27 '22 22:09

Ricardo Saporta