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
vec <- 2119.1921
trunc(vec)
Output
[1] 2119
Example 2: Calculating for negative values
vec <- -2119.1921
trunc(vec)
Output
[1] -2119
Example 3: Using 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
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
That’s it!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.