Contact
R does not round 2.5 to 3
Data scientist in Basel
508
post-template-default,single,single-post,postid-508,single-format-standard,bridge-core-3.1.8,qode-page-transition-enabled,ajax_fade,page_not_loaded,,qode_grid_1300,side_area_uncovered_from_content,overlapping_content,qode-content-sidebar-responsive,qode-theme-ver-30.5,qode-theme-bridge,disabled_footer_top,qode_header_in_grid,wpb-js-composer js-comp-ver-7.6,vc_responsive

R does not round 2.5 to 3

R does not round 2.5 to 3

In R’s default round() functions, odd numbers ending with .5 are rounded up (1.5 becomes 2), but even numbers are rounded down (2.5 becomes 2, rather than 3). This is compliant with a norm on rounding as outlined in the R documentation, but sometimes inconvenient.


The rounding behavior of R is like this

[code lang=”R”]for (i in c(1.5, 2.5, 3.5, 4.5)) print(c(i,round(i,0)))
# original rounded
# [1] 1.5 2.0
# [1] 2.5 2.0
# [1] 3.5 4.0
# [1] 4.5 4.0
[/code]

You need to round 2.5 to 3 nevertheless? I needed this at some point to break an otherwise infinite loop in my iterative parameter approximation. Here is a solution from Stock Overflow who had it from statistically significant.

[code lang=”R”]round2 <- function(x, n) {
posneg = sign(x)
z = abs(x)*10^n
z = z + 0.5
z = trunc(z)
z = z/10^n
z * posneg
}
[/code]

Where x is the object we want to round, and n is the number of digits just like in the standard rounding function. Rounding behavior looks like this

[code lang=”R”]for (i in c(1.5, 2.5, 3.5, 4.5)) print(c(i,round2(i,0)))
# original rounded
# [1] 1.5 2.0
# [1] 2.5 3.0
# [1] 3.5 4.0
# [1] 4.5 5.0
[/code]