R - round() Function
The R round() function rounds the values in its first argument to the specified number of decimal places (default 0). In special cases it returns the following:
- If the argument is NaN or infinity, then the result is the same as the argument.
Syntax
round(x, digits)
Parameters
x |
Required. Specify column to round off. |
digits |
Optional. Specify number of decimal places to which value has to be round off. Default is 0. |
Return Value
Returns the integral value that is nearest to the argument value.
Example: Rounding off the values
In the example below, round() function is used to round the specified number.
#operating on single element atomic vector print(round(-1)) print(round(0.5)) print(round(2.0)) cat("\nOperating on vector\n") #operating on vector v <- c(10.3, 10.5, 10.7, -10.3, -10.5, -10.7) print(round(v)) cat("\nOperating on matrix\n") #operating on matrix m <- matrix(c(-10.3, -10.5, -10.7, 100.2, Inf, NaN), nrow=2) print(round(m)) cat("\nOperating on first column of matrix\n") #operating on first column of matrix print(round(m[,1]))
The output of the above code will be:
[1] -1 [1] 0 [1] 2 Operating on vector [1] 10 10 11 -10 -10 -11 Operating on matrix [,1] [,2] [,3] [1,] -10 -11 Inf [2,] -10 100 NaN Operating on first column of matrix [1] -10 -10
Example: Rounding off to certain decimal places
Consider one more example where a numeric vector is rounded off to 2 decimal places.
#creating a vector v <- c(10.33333, 10.567, 10.7, -10.35, -10.534, 10/3) #printing the vector after rounding #off to 2 decimal places print(round(v, 2))
The output of the above code will be:
[1] 10.33 10.57 10.70 -10.35 -10.53 3.33
❮ R Math Functions