Round Numbers in R

How to Round Numbers in R

This page will show you how to round numbers in R and specify the number of decimal places to use. In R the command “round” is used to round numbers. The below will show you how round works and provides some examples of rounding.

The first example rounds the numbers in the field Score in the data frame StudentData to no decimal places and saves the rounded numbers back to the same field. Rounding to no decimal places is the default rounding in R if the number of decimal places is not specified. Note that the field that is being rounded must be numeric or R will return the error “round not meaningful for factors”.

# Round numbers in R
StudentData$Score<-round(StudentData$Score)

The problem with the above is that the unrounded field Score data has been lost. In this example, R saves the rounded Score values in a new field ScoreRounded, preserving the Score data for later use.

# Round numbers in R
StudentData$ScoreRounded<-round(StudentData$Score)

The next example shows how to specify the number of decimal places to round to. In this case R will round to 2 decimal places.

# Round numbers in R
StudentData$ScoreRounded<-round(StudentData$Score, 2)

There are other options that can be used with round. See official R-manual page on round to learn more: http://stat.ethz.ch/R-manual/R-devel/library/base/html/Round.html.

Practice

To practice formatting data in R, try the exercises in this string manipulation tutorial.

Thanks for reading! This website took a great deal of time to create. If it was helpful to you, please show it by sharing with friends, liking, or tweeting! If you have any thoughts regarding this R code please post in the comments.

JM

Leave a Reply

Your email address will not be published. Required fields are marked *