函数四舍五入到R 中最接近的非零小数位(包括负数)



我正在寻找一种四舍五入到 R 中最接近的非零小数位的方法,如果四舍五入到两位产生零。预期输出将是

my_round(12.5624)
> 12.56
my_round(-0.64010)
> -0.64
my_round (0.000026)
> 0.00003
my_round(-0.00072451)
> -0.0007

我目前的想法是四舍五入并检查四舍五入到两位数是否产生零:如果是这样,我将遍历一系列值并迭代 X 位四舍五入,直到我收到一个非零值。但是,这似乎笨拙,效率低下,并且最多限制为特定数量的零位数(在下面的代码中为10)。我的尝试(无法正常工作)如下:

my_round <- function(x) {
res <- round(x, 2)
if (res != 0) {
return(res)
}
for (i in seq(3:10)) {
res <- round(x, i)
if (res != 0) {
return (res)
}
}
return(NA)
}

这样做的问题是输出如下所示

my_round(0.00007702)
> 0.0001

相反,我正在寻找

my_round(0.00007702)
> 0.00008

任何建议将不胜感激。

我们可以将函数更改为

my_round <- function(x)  {
x1 <- round(x, 2)
if(round(x, 2) == 0) {
n1 <- stringr::str_locate(x, "[^-0.]")[1] -  str_locate(x, fixed("."))[1]
print(n1)
x1 <- round(x, n1)

}
return(x1)

}

-测试

> my_round(12.5624)
[1] 12.56
> my_round(-0.64010)
[1] -0.64
> my_round(0.000026)
[1] 5
[1] 0.00003
> my_round(-0.00072451)
[1] 4
[1] -0.0007
> my_round(0.00007702)
[1] 5
[1] 0.00008

也许是这样的:

my_round = function(x, n=2) {
max(abs(round(x, n)), abs(signif(x, 1))) * sign(x)
}
my_round(12.5624)
# [1] 12.6
my_round(-0.64010)
# [1] -0.64
my_round (0.000025)
# [1] 2e-05
my_round(-0.00072451)
# [1] -7e-04
my_round(0.00007702)
# [1] 8e-05

请注意,my_round(0.000025)应该给出2e-05,根据"四舍五入到偶数"的标准规则(有关此舍入规则的解释,请参阅?round)。

最新更新