R round() Function - Rounding and Truncation
The R round() function is used to round numbers, with an option to specify the number of decimal places.
The syntax of the round() function is as follows:
round(x, digits = 0)
Parameter Description:
-
x Input number or numeric vector.
-
digits The number of decimal places to keep; 0 by default, meaning round to an integer.
Example
Create a numeric vector
x
<-
c
(
3.14159
,
2.71828
,
1.41421
,
5.6789
)
Round to an integer
(
round
(
x
)
)
Keep 2 decimal places
(
round
(
x, digits
=
2
)
)
Keep 3 decimal places
(
round
(
x, digits
=
3
)
)
The output of the code above is:
[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)
(
"ceiling rounds up:"
)
(
ceiling
(
x
)
)
floor: round down (the largest integer not greater than x)
(
"floor rounds down:"
)
(
floor
(
x
)
)
trunc: truncate toward zero
(
"trunc truncation:"
)
(
trunc
(
x
)
)
signif: keep significant digits
(
"signif(pi, 4) 4 significant digits:"
)
(
signif
(
pi
,
4
)
)
The output of the code above is:
[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.142
R Language Examples