forked from tidyverse/design
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcs-rgb.qmd
69 lines (57 loc) · 1.61 KB
/
cs-rgb.qmd
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Case study: `rgb()` {#sec-cs-rgb}
```{r}
#| include = FALSE
source("common.R")
```
Interface:
- Function name and argument names.
- `alpha` has no default but isn't required.
- `names` not required (imo).
- `maxColorValue` doens't have most useful default, and not really needed (imo).
- Data frame rather than matrix.
- Error if function specification is correct
- Check for data type, not missingness.
```{r}
#| error = TRUE
library(rlang)
rgba <- function(r, g, b, a = NULL) {
if (is.data.frame(r)) {
df <- r
if (!ncol(df) %in% c(3L, 4L)) {
abort("If `r` is data frame, it must have 3 or 4 columns.")
}
if (!missing(b) || !missing(g) || !missing(a)) {
abort("If `r` is a data frame, `b`, `g`, and `a` must not be set.")
}
r <- df[[1L]]
g <- df[[2L]]
b <- df[[3L]]
if (ncol(df) == 4) {
a <- df[[4L]]
}
}
rgb(r, g, b, alpha = a, maxColorValue = 255)
}
rgba(16, 16, 16)
rgba(data.frame(16, 16, 16))
rgba(data.frame(16, 16))
rgba(data.frame(16, 16, 16), 1)
```
```{r}
rgba <- function(r, g, b, a = NULL) {
if (is.data.frame(r)) {
df <- r
if (!all(c("r", "g", "b")) %in% names(df)) {
abort("If first argument is a data frame, it must have r, g, and b columns.")
}
if (!missing(b) || !missing(g) || !missing(a)) {
abort("If `r` is a data frame, `b`, `g`, and `a` must not be set.")
}
} else {
# Handles vectorisation
df <- tibble(r = r, g = g, b = b, a = a)
}
# Assumes this function checks types and gives informative error messages
rgb(df$r, df$g, df$b, alpha = df$a, maxColorValue = 255)
}
```