In this article we will work on learning how to round off numbers in R using round() command.


Theory

Did you ever come across a problem of rounding numbers to the decimals you need after doing the required calculations?

I’m sure you did!

There are various cases where you are required to perform a lot of mathematical actions to get the number you are looking for. It can be anything: costs, dimensions, durations, and so on.

For the purposes of this article we will consider a simple example:
You are running a firm that received a payment for services in the amount of $10,450.89. You have 7 employees that were working on a project, each to be paid the same amount.

The math here is simple, you take out a calculator and divide $10,450 by 7 to get $1,492.857.

I agree, it’s a simple example, and you can do the rounding manually here. But with more complex examples, you will often see numbers with more than 6 decimal places.

So how do we go about it?

Let’s learn how to round off numbers in R.



Application

Below are the steps we are going to take to make sure we do master the skill of rounding off numbers in R:

  1. Basic round() command description
  2. Creating a sample number in R
  3. Rounding off numbers R



Part 1. Basic round() command description

The short theoretical explanation of the function is the following:

round(number, digits=n)

Here, “number” refers to the number you would like to round.

And “n” is the number of decimal places.



Part 2. Creating a sample number in R

Remember the scenario I mentioned above?

We have $10,450 that we need to divide between 7 employees.

Let’s perform the mathematic operations using the following command:


sample_number<-10450/7

The number that R generates from this operation is 1492.85714285714.

Clearly we can't pay out .85714285714. We need to round off the number to 2 decimal places.

So how do we do it?

Let's see how to round off numbers in R!



Part 3. Rounding off numbers in R

Our goal now is to round off the "sample_number" to 2 decimal places.

Going back to the formula, our "number" component will be "sample_number" and our "n" component will be 2.

At this point we are all set to round off numbers in R!

You can do it using the following code:


rounded_number<-round(sample_number, digits=2)

After this rounding operation, our "rounded_number" becomes 1492.86.



If you are interested to learn more about data manipulation in R, you can find more articles here.