2

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)

4

3 回答 3

1

您可以将这里sprintf讨论的功能和想法结合起来。

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"
于 2014-07-24T09:09:00.367 回答
1

尝试这个:

## 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)

输出:

0.02 0.24  2.4   24  240 0.90  200
于 2016-01-07T15:56:23.257 回答
0

对于这个特定问题,一种可能的解决方案似乎是:

    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)
     }
于 2014-07-25T05:17:27.327 回答