0

This question does not duplicate Round up from 0.5. I am looking for different behavior. I want -0.5 to round up to 0, and 0.5 to round up to 1. This behavior needs to work consistently for all numbers with decimal values of -0.5 or 0.5.

Here is the result I want:

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

With round I get this:

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

With ceiling I get this:

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

janitor::round_half_up() doesn't seem to work on negative numbers.

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

floor() obviously doesn't do what I'm looking for, and neither does the round2() function that is sometimes suggested for other questions about rounding.

Thank you!

Susie Derkins
  • 2,506
  • 2
  • 13
  • 21
  • You can write a custom function specifying two conditions for those two specific values and leave the rest to `ceiling`. – Anoushiravan R Dec 23 '21 at 21:23
  • @AnoushiravanR this is only a sample dataset to indicate the behavior I want. There are many other values in the dataset and I need consistent output for all values. – Susie Derkins Dec 23 '21 at 21:27
  • `trunc` would get you most of the way there, but it doesn't round, per se. It just chops off the decimals. – jdobres Dec 23 '21 at 21:27
  • 1
    Can you just add a small number to all data? like `a=c(-0.7, -0.5, 0, 0.2, 0.5); round(a+0.001)`. Choose a small enough number for your dataset. – Bing Dec 23 '21 at 21:29
  • @Bing that might work. I'll have to try it on my full dataset and run some checks. – Susie Derkins Dec 23 '21 at 21:47
  • Actually, my answer is already in "Round up from 0.5". – user2554330 Dec 23 '21 at 21:52

1 Answers1

3

The usual way to get everything to round 0.5 up is to use 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

Created on 2021-12-23 by the reprex package (v2.0.1)

user2554330
  • 37,248
  • 4
  • 43
  • 90