-
Notifications
You must be signed in to change notification settings - Fork 2
/
functions_ungrouped.Rmd
71 lines (56 loc) · 1.96 KB
/
functions_ungrouped.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
---
title: "Non-Categorised Functions"
author: "Hauke Sonnenberg"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Non-Categorised Functions}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
### Function `arglist()`
Have you ever seen something like the following?
```{r}
x <- seq(-pi, pi, pi/10)
par(mfrow = c(1, 2), mar = c(2, 2, 1, 1))
plot(x, sin(x), xlab = "x", ylab = "sin(x)", pch = 16, type = "b", cex = 0.5)
plot(x, cos(x), xlab = "x", ylab = "cos(x)", pch = 16, type = "b", cex = 0.5)
```
Do you spot the repetition? What if you want to change the plot character `pch`
or the `type` of the plot or the character extension factor `cex` in both
plots at the same time?
```{r}
# Define common arguments
common <- list(x = x, pch = 16, xlab = "x", type = "b", cex = 0.5)
# Call the plot function with the common arguments, extended by
# call-specific arguments
par(mfrow = c(1, 2), mar = c(2, 2, 1, 1))
do.call(plot, kwb.utils::arglist(common, y = sin(x), ylab = "sin(x)"))
do.call(plot, kwb.utils::arglist(common, y = cos(x), ylab = "cos(x)"))
```
The function `arglist()` merges the contents of one or more lists by allowing
to overwrite existing list elements. In the above example, the list of `common`
arguments is just extended. Elements in this list could also be overwritten,
such as the argument `cex` in the following:
```{r}
do.call(
what = plot,
args = kwb.utils::arglist(common, y = sin(x), ylab = "sin(x)", cex = 1)
)
```
This pattern of calling a function with an extended argument list is so common
that I wrote a function `callWith()` that allows to write the above shorter:
```{r}
kwb.utils::callWith(plot, common, y = sin(x), ylab = "sin(x)", cex = 1)
```
But this will be explained later...
### Function DIN.A4()
### Function expandGrid()
### Function makeUnique()
### Function randomValuesWithSum()