I want to format figures with 2 significant digits using formatC
. But it has a strange behaviour. Here are the figures:
(x <- data.frame( cil = c(1.234, 0.444, 0.712, 0.999, 1.999)
, ciu = c(1.812, 1.234, 0.999, 1.199, 2.690)
)
)
x$ci <- with(x,paste("("
, formatC(cil, format="g", digits=2, flag="#")
, "-"
, formatC(ciu, format="g", digits=2, flag="#")
,")"
)
)
x
And here are the results:
cil ciu ci
1 1.234 1.812 ( 1.2 - 1.8 )
2 0.444 1.234 ( 0.44 - 1.2 )
3 0.712 0.999 ( 0.71 - 1.0 )
4 0.999 1.199 ( 1.0 - 1.2 )
5 1.999 2.690 ( 2. - 2.7 )
In case 5 I expected 2.0 and not 2.. Is there an explanation for this? Did I something wrong with the definition of the parameters?
New curious behaviour: leading space depending if figure was rounded down or up:
y1 <- 18.96552
y2 <- 17.04545
formatC(y1, format="g", digits=2,flag="#")
[1] " 19."
formatC(y2, format="g", digits=2,flag="#")
"17."
Can be solved with trim (from gdata). But anyway, it is a strange behaviour as the first one, which by the way persists (V4.32).
To illustrate what I was saying in my comment, you can do :
or the following, to suppress the spaces before or after the brackets :
NB : you actually can get the same result using function
formatC
but withformat="f"
instead of"g"
.UPDATE :
I guess the fact that
0
is not printed after2.
is just a bug in some R versions (weirder thing : if you try the line with2.01
instead of1.999
, you'll get"2.0"
...).To make it work with your line and obtain exactly what you want, just add
round
function :