trunc in R: How to Use trunc() Function in R

The trunc() method in R is truncate, which rounds to the nearest integer in the direction of 0. The trunc() function truncates the values in the decimal places.

trunc() in R

The trunc() is a built-in R function that rounds the values to zero decimal points. It takes data that can be either a vector, string, or data frame and returns the converted integer number.

The trunc() method can convert float to int values.

Syntax

trunc(data)

Parameters

The trunc() function takes data as an input string, vector, or data frame.

Return value

The trunc() method returns reduced the input values to zero decimal place and converted it into an int number.

Example

trunc(2119.1921)

Output

[1] 2119

You can see from the output that the trunc() method reduced the 2119.1921 values to zero decimal place and converted it into an int number.

Calculating trunc() value of Negative values in R

To calculate the trunc value of the negative value, use the trunc() method and pass the negative value as a parameter.

trunc(-2119.1921)

Output

[1] -2119

Applying trunc() method to a Vector

To create a Vector in R, use the c() function or ( : ) colon operator. Apply the trunc() method to a Vector.

rv <- c(1.1, 21.19, 1.9, 11, -46)
trunc(rv)

Output

[1] 1 21 1 11 -46

You can see that the trunc() function has returned the int values with zero decimal points.

Applying trunc() function to the data frame column

To create a data frame, use the data.frame() function. In this example, we will use the mtcars dataset, apply the trunc() function to the wt column, and see the output.

data(mtcars)
cat("\n")
cat("Trunc values of wt column", "\n")
cat("\n")
trunc(mtcars$wt)

Output

Trunc values of wt column

[1] 2 2 2 3 3 3 3 3 3 3 3 4 3 3 5 5 5 2 1 1 2 3 3 3 3 1 2 1 3 2 3 2

You can see that the trunc() function has reduced/returned all the values present in the mtcars dataset with zero decimal points.

That is it for the trunc() method in R.

See also

R round()

R floor()

R ceiling()

R absolute value

Leave a Comment