R round Function

The R round method is one of the Math functions that round a specific number or an expression to the nearest value. Let us see how to use round with an example. The syntax of the round in this Programming language is as shown below.

# numeric_Expression to nearest value 
round(numeric_Expression)

# decimal points to specified integer_value 
round(numeric_Expression, integer_value)

Numeric_Expression: It can be a numeric value or a valid numerical expression.

  • If the numeric_Expression is a positive or negative numeric value, it returns the nearest ceiling value.
  • If it is not a number (NaN), then it returns NaN. And if it is positive or negative infinity, the function returns the same.

R round Function example

In this program, We are going to return the round values of different data and display the output.

# Use on Positive  Value
round(45.56)
round(525.4999)

# Use on Negative values
round(-140.825)
round(-13.23)

# Expression
round(140.986 + 122.456 - 220.4233 + 12.67)

# on vectors
number <- c(-22.26, 456.94, 2.50, 2.51, -36.49, -813.111 , -525.123)
round(number)
Round Function on integers and vectors 1

Example 2

In this Program, We are going to round the decimal values of different data & display the output.

> round(45.565, 0)
[1] 46
> 
> # decimal points to 1 
> round(525.419299, 1)
[1] 525.4
> round(525.419299, 2)
[1] 525.42
> 
> # Use on Negative values
> round(-140.825, 2) 
[1] -140.82
> round(-13.239, 2)
[1] -13.24
> 
> # Expression
> round((140.986 + 122.4563256 - 220.4233 + 12.67), 2)
[1] 55.69
> 
> # vectors
> number <- c(-22.26, 456.94, 2.50, 2.591, -36.49, -813.111 , -525.123)
> round(number, 1)
[1]  -22.3  456.9    2.5    2.6  -36.5 -813.1 -525.1

R round Function Example 3

In this program, We are going to apply the round function to List data and display the output. For this example, we are using the airquality data set provided by R.

#Dataset We are going to use
airquality

# Applying on Airquality Wind Data
round(airquality$Wind)

round(airquality$Wind, 1)

This function also allows you to round the numeric values in a database or table columns. In this example, We are going to round all the records present in the [Standard Cost] and [Sales Amount] columns. For this, We are going to use the below-shown CSV file data.

TIP: Please refer to the Read CSV Function article to understand the steps involved in importing the CSV file.

CODE

getwd()

#Datat We are going to use
product <- read.csv("Product_Data.csv", TRUE, sep = ",")
print(product)

# Applying on Standard Cost, and Sales Amount
round(product$StandardCost)
round(product$StandardCost, 1)

round(product$SalesAmount)
round(product$SalesAmount, 2)