Home » excel » R: How to define round function like in Excel?

R: How to define round function like in Excel?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I just got to know that R or Python have different ways of defining the round function compared to Excel.

Statistical argument aside, my business users are primarily Excel users. And this has led to some confusion as the numbers generated by R/Python scripts can differ due to this rounding convention.

It seems to me that Excel always ’round up’ when it needs to calculate numbers like 1.5, 2.5, 3.5, etc while R/Python will round to the nearest even number instead.

Potentially there’re other assumptions I’m not aware of which differentiate both Excel and R/Python.

Is there any way to implement the exact round function from Excel in R?

In Excel

enter image description here

In R

enter image description here

How to&Answers:

Based on the observed behaviour that round in Excel rounds away from zero for numbers ending in 0.5, it could be replicated in R with:

> x <- c(-1.5, -0.5, 0.5, 1.5, 2.5, 3.5)
> round(x+2*sign(x)*.Machine$double.eps)
# [1] -2 -1  1  2  3  4