R round() Function - Rounding and Truncation
The R round() function is used to round numeric values and can specify the number of decimal places to keep.
The syntax of the round() function is as follows:
round(x, digits = 0)
Parameter description:
xInput a numeric value or numeric vector.
digitsNumber of decimal places to keep, default is 0, meaning round to an integer.
Example
# Create a numeric vector
x <- c(3.14159, 2.71828, 1.41421, 5.6789)
# Round to integer
print(round(x))
# Keep 2 decimal places
print(round(x, digits = 2))
# Keep 3 decimal places
print(round(x, digits = 3))
x <- c(3.14159, 2.71828, 1.41421, 5.6789)
# Round to integer
print(round(x))
# Keep 2 decimal places
print(round(x, digits = 2))
# Keep 3 decimal places
print(round(x, digits = 3))
Executing the above code produces the following output:
[1] 3 3 1 6 [1] 3.14 2.72 1.41 5.68 [1] 3.142 2.718 1.414 5.679
R also provides several other rounding functions, each with different behavior:
Example
x <- c(3.7, -3.7, 3.2, -3.2)
# ceiling: round up (the smallest integer not less than x)
print("ceiling round up:")
print(ceiling(x))
# floor: round down (the largest integer not greater than x)
print("floor round down:")
print(floor(x))
# trunc: round toward zero
print("trunc truncation:")
print(trunc(x))
# signif: keep significant digits
print("signif(pi, 4) 4 significant digits:")
print(signif(pi, 4))
# ceiling: round up (the smallest integer not less than x)
print("ceiling round up:")
print(ceiling(x))
# floor: round down (the largest integer not greater than x)
print("floor round down:")
print(floor(x))
# trunc: round toward zero
print("trunc truncation:")
print(trunc(x))
# signif: keep significant digits
print("signif(pi, 4) 4 significant digits:")
print(signif(pi, 4))
Executing the above code produces the following output:
[1] "ceiling 向上取整:" [1] 4 -3 4 -3 [1] "floor 向下取整:" [1] 3 -4 3 -4 [1] "trunc 截断:" [1] 3 -3 3 -3 [1] "signif(pi, 4) 4位有效数字:" [1] 3.142Other extensions
R Language Example