Reputation: 31
I am trying to apply a sequential rounding function on any real number so that the following condition is met: "Numbers should be reported with no more than two decimal digits and no more than two significant figures".
For example:
0.0236 should be reported as 0.02
0.236 should be reported as 0.24
2.36 should be reported as 2.4
23.6 should be reported as 24
236 should be reported as 240
It seems that whenever there are trailing zeros after rounding with round
and signif
, these are omitted (e.g. 0.90023 becomes 0.9 instead of 0.90). I have tried the following piece of code:
my_round <- function(x1) {
x2 <- formatC(x1, digits=2, format="f", drop0trailing=FALSE)
x2 <- as.numeric(x2)
x3 <- formatC(x2, digits=2, format="fg", flag="#", drop0trailing=FALSE)
x3 <- as.numeric(x3)
print(x3)
}
This works fine for any number except those like 195 (more than two significant figures in their integer part) which remains 195 instead of getting rounded to 200.
I would appreciate any help provided on this topic.
(R v3.1.0, 2014-04-10)
Upvotes: 3
Views: 2096
Reputation: 133
Try this:
## Install the prettyprint package
install.packages("devtools")
devtools::install_github("prettyprint/prettyprint")
##
library(prettyprint)
x = c(0.0236, 0.236, 2.36, 23.6, 236, 0.90023, 195)
pp(x, digits = 2)
Output:
0.02 0.24 2.4 24 240 0.90 200
Upvotes: 2
Reputation: 31
It seems that one possible solution for this particular problem is:
my_round <- function(x1) {
x2 <- formatC(x1, digits=2, format="f", drop0trailing=FALSE)
x2 <- as.numeric(x2)
if(x2<100) {
x3 <- formatC(x2, digits=2, format="fg", flag="#")
x3 <- as.numeric(x3)
}
else {
x3 <- signif(x2, digits=2)
}
print(x3)
}
Upvotes: 0
Reputation: 1049
You can combine the function sprintf
and the ideas discussed here.
ceil.ten <- function(x)
if (x > 100) ceiling(x/10)*10 else x
sprintf("%.2f", ceil.ten(0.0236))
# [1] "0.02"
sprintf("%.2f", ceil.ten(0.236))
# [1] "0.24"
sprintf("%.2f", ceil.ten(2.36))
# [1] "2.36"
sprintf("%.2f", ceil.ten(23.6))
# [1] "23.60"
sprintf("%.2f", ceil.ten(236))
# [1] "240.00"
sprintf("%.2f", ceil.ten(195))
# [1] "200.00"
Upvotes: 2