How to round up to whole number in R?
Asked Answered
C

2

45

Is it possible to round up to the nearest whole number in R? I have time-stamped data and I want to round up to the nearest whole minute, to represent activities during this minute.

For example, if time is presented in minutes.seconds format:

x <- c(5.56, 7.39, 12.05, 13.10)
round(x, digits = 0)
[1]  6  7 12 13

My anticipated output would instead be:

round(x, digits = 0)
[1]  6  8 13 14

I understand this is confusing but when I am calculating activity per minute data, rounding up to the nearest minute makes sense. Is this possible?

Carberry answered 17/4, 2017 at 3:34 Comment(0)
S
78

We can use ceiling to do the specified rounding

ceiling(x)
#[1]  6  8 13 14
Scheider answered 17/4, 2017 at 3:35 Comment(0)
R
1

Another way round up is to integer-divide the negation and negate the result back:

-(-x%/%1)
#[1]  6  8 13 14

Both the above approach and ceiling() fall subject to floating point precision issues which causes a bug. For example 0.28/0.005 is 56 but ceiling(0.28/0.005) is 57. To safeguard against such possibilities, we could first round the numbers up to a certain digit (say, 8) and take ceiling of them.

x <- 0.28/0.005

ceiling(x)               # <--- not OK
ceiling(round(x, 8))     # <--- OK
Retinoscopy answered 21/5, 2024 at 21:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.