R trunc() Function

The trunc() function in R is used to remove the fractional part of the value, effectively rounding it down towards zero. 

This function acts as a “ceiling()” function for negative numbers and a “floor()” function for positive numbers. For example, trunc(3.14) returns 3 and trunc(-2.7) returns -2.

Syntax

trunc(data)

Parameters

data: It takes data as an input string, vector, or data frame.

Return value

It reduces the input values to zero decimal places and converts them into int numbers.

Example 1: Simple usage of trunc() function

Simple usage of trunc() function

vec <- 2119.1921

trunc(vec)

Output

[1] 2119

Example 2: Calculating for negative values

Calculating trunc() value of negative values

vec <- -2119.1921

trunc(vec)

Output

[1] -2119

Example 3: Using vector

Using the trunc() method with a vector

vec <- c(1.1, 21.19, 1.9, 11, -46)

trunc(vec)

Output

[1] 1 21 1 11 -46

Example 4: Using data frame column

Using the trunc() function with data frame column

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7.9, 8.1, 9.5)
)
cat("Before truncating col3", "\n")
df

# Sort the multiple data frame columns

cat("After truncating the 'col3'", "\n")
trunc(df$col3)

Output

Using trunc() function with data frame

That’s it!

Leave a Comment