从 0.5 向上舍入并从 R 中的 -0.5 向上舍入

Round up from 0.5 AND round up from -0.5 in R

这个问题不重复Round up from 0.5。我正在寻找不同的行为。我希望 -0.5 舍入为 0,0.5 舍入为 1。此行为需要对所有十进制值为 -0.5 或 0.5 的数字一致地起作用。

这是我想要的结果:

c(-0.7, -0.5, 0, 0.2, 0.5)
[1] -1 0 0 0 1

使用 round 我得到这个:

> round(c(-0.7, -0.5, 0, 0.2, 0.5))
[1] -1  0  0  0  0

使用 ceiling 我明白了:

> ceiling(c(-0.7, -0.5, 0, 0.2, 0.5))
[1] 0 0 0 1 1

janitor::round_half_up() 似乎不适用于负数。

> round_half_up(c(-0.7, -0.5, 0, 0.2, 0.5))
[1] -1 -1  0  0  1

floor() 显然不能满足我的要求,round2() 函数也不能满足其他舍入问题。

谢谢!

使所有内容向上取整 0.5 的常用方法是使用 floor(x + 0.5):

x <- c(-0.7, -0.5, 0, 0.2, 0.5)
floor(x + 0.5)
#> [1] -1  0  0  0  1

reprex package (v2.0.1)

于 2021-12-23 创建