-
Notifications
You must be signed in to change notification settings - Fork 5
/
08-tidbits.Rmd
51 lines (41 loc) · 1.8 KB
/
08-tidbits.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Interesting tidbits {#tidbits}
```{r include=FALSE}
# Every file must contain at least one R chunk due to the linting process.
```
## Rounding
For rounding numerical values we have the function `round(x, digits = 0)`.
This rounds the value of the first argument to the specified number of decimal
places (default 0).
```{r}
round(c(-1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5))
```
This probably looks different to what you were expecting as at school we were
generally taught that when rounding a 5 we go up if a positive value and down if
a negative value. R, however, implements a different standard. We can see this
by looking at the documentation (`?round`)
> Note that for rounding off a 5, the IEC 60559 standard (see also ‘IEEE 754’)
is expected to be used, *‘go to the even digit’*. Therefore `round(0.5)` is `0`
and `round(-1.5)` is `-2`. However, this is dependent on OS services and on
representation error (since e.g. `0.15` is not represented exactly, the
rounding rule applies to the represented number and not to the printed number,
and so `round(0.15, 1)` could be either `0.1` or `0.2`).
To implement what we consider normal rounding we can install use the `janitor`
package and the function `round_half_up`
```{r, warning=FALSE}
library(janitor)
janitor::round_half_up(c(-1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5))
```
If we do not have access to the package (or do not want to depend on the
package) then we can implement^[see [stackoverflow](https://stackoverflow.com/questions/12688717/round-up-from-5/12688836#12688836)
discussion for a discussion of the implementation]
```{r}
round_half_up_v2 <- function(x, digits = 0) {
posneg <- sign(x)
z <- abs(x) * 10 ^ digits
z <- z + 0.5
z <- trunc(z)
z <- z / 10 ^ digits
z * posneg
}
round_half_up_v2(c(-1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5))
```