R - trunc() Function
The R trunc() function is used to round the given number towards zero. It returns the nearest integral value with absolute value less than the argument. In special cases it returns the following:
- If the argument value is already an integer, then the result is the same as the argument.
- If the argument is NaN or infinity, then the result is the same as the argument.
Syntax
trunc(x)
Parameters
x |
Required. Specify column to compute on. |
Return Value
Returns the integer value by rounding the specified number towards zero.
Example:
In the example below, trunc() function is used to round the specified number towards zero.
#operating on single element atomic vector print(trunc(-1)) print(trunc(0.5)) print(trunc(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(trunc(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(trunc(m)) cat("\nOperating on first column of matrix\n") #operating on first column of matrix print(trunc(m[,1]))
The output of the above code will be:
[1] -1 [1] 0 [1] 2 Operating on vector [1] 10 10 10 -10 -10 -10 Operating on matrix [,1] [,2] [,3] [1,] -10 -10 Inf [2,] -10 100 NaN Operating on first column of matrix [1] -10 -10
❮ R Math Functions