Here are five ways to round numbers in R:
- round(): It rounds values to a specified number of decimal places.
- signif(): It rounds values to several significant digits.
- ceiling(): It rounds values up to the nearest integer.
- floor(): It rounds values down to the nearest integer.
- trunc(): It truncates (cuts off) decimal places from values.
Method 1: Using round(x, digits)
num_vec <- c(11.23, 46.56, 21.89)
# round each number to one decimal place
round(num_vec, 1)
Output
[1] 11.2 46.6 21.9
Method 2: Using signif()
Rounding to a specified number of significant digits means keeping the first few most significant digits and rounding off the rest.
num_vec <- c(11.23, 46.56, 21.89)
# round each number to one significant digit
signif(num_vec, 1)
Output
[1] 10 50 20
Here is the explanation of the output:
- 11.23 is rounded to 10 because the first significant digit is 1.
- 46.56 is rounded to 50 because the first significant digit is 4.
- 21.89 is rounded to 20 because the first significant digit is 2.
Method 3: Using ceiling()
num_vec <- c(11.23, 46.56, 21.89)
ceiling(num_vec)
Output
[1] 12 47 22
Here is the explanation of the output:
- ceiling(11.23) rounded from 11.23 up to 12.
- ceiling(46.56) rounded from 46.56 up to 47.
- ceiling(21.89) rounded from 21.89 up to 22.
Method 4: Using floor()
num_vec <- c(11.2313, 46.5633, -21.89)
floor(num_vec)
Output
[1] 11 46 -22
Method 5: Using trunc()
num_vec <- c(19.21, 21.4619, -21.18)
trunc(num_vec)
Output
[1] 19 21 -21
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.
This a great feature. Really Cool. Respect an opportunity to get super stats regarding units blogs and forums, too! I serious like everything about this wundabar artical…