-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathfunctions.qmd
203 lines (160 loc) · 7.19 KB
/
functions.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
---
execute:
freeze: auto
---
# Functions {#functions}
```{r, message = FALSE, warning = FALSE, echo = FALSE}
knitr::opts_knit$set(root.dir = fs::dir_create(tempfile()))
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", eval = TRUE)
```
```{r, message = FALSE, warning = FALSE, echo = FALSE, eval = TRUE}
library(targets)
library(tarchetypes)
```
[`targets`](https://github.com/ropensci/targets) expects users to adopt a function-oriented style of programming. User-defined R functions are essential to express the complexities of data generation, analysis, and reporting. This chapter explains what makes functions useful and how to leverage them in your pipelines. It is based on the example from the [walkthrough chapter](#walkthrough).
## Problems with script-based workflows
Traditional data analysis projects consist of imperative scripts, often with with numeric prefixes.
```
01-data.R
02-model.R
03-plot.R
```
To run the project, the user runs each of the scripts in order.
```{r, eval = FALSE}
source("01-data.R")
source("02-model.R")
source("03-plot.R")
```
Each script executes a different part of the workflow.
```{r, eval = FALSE}
# 01-data.R
library(tidyverse)
data <- "data.csv" %>%
read_csv(col_types = cols()) %>%
filter(!is.na(Ozone))
write_csv(data, "data.rds")
```
```{r, eval = FALSE}
# 02-model.R
library(biglm)
library(tidyverse)
data <- read_rds("data.rds", col_types = cols())
model <- lm(Ozone ~ Temp, data) %>%
coefficients()
saveRDS(model, "model.rds")
```
```{r, eval = FALSE}
# 03-plot.R
library(tidyverse)
model <- readRDS("model.rds")
data <- readRDS("data.rds")
plot <- ggplot(data) +
geom_point(aes(x = Temp, y = Ozone)) +
geom_abline(intercept = model[1], slope = model[2]) +
theme_gray(24)
ggsave("plot.png", plot)
```
Although this approach may feel convenient at first, it scales poorly for medium-sized workflows. These [imperative](https://en.wikipedia.org/wiki/Imperative_programming) scripts are monolithic, and they grow too large and complicated to understand or maintain.
## Functions
Functions are the building blocks of most computer code. They make code easier to think about, and they break down complicated ideas into small manageable pieces. Out of context, you can develop and test a function in isolation without mentally juggling the rest of the project. In the context of the whole workflow, functions are convenient shorthand to make your work easier to read.
In addition, functions are a nice mental model to express data science. A data analysis workflow is a sequence of transformations: datasets map to analyses, and analyses map to summaries. In fact, a function for data science typically falls into one of three categories:
1. Process a dataset.
2. Analyze a dataset.
3. Summarize an analysis.
The example from the [walkthrough chapter](#walkthrough) is a simple instance of this structure.
## Writing functions
Let us begin with our [imperative](https://en.wikipedia.org/wiki/Imperative_programming) code for data processing. Every time you look at it, you need to read it carefully and relearn what it does. And test it, you need to copy the entire block into the R console.
```{r, eval = FALSE}
data <- "data.csv" %>%
read_csv(col_types = cols()) %>%
filter(!is.na(Ozone))
```
It is better to encapsulate this code in a function.
```{r, eval = FALSE}
get_data <- function(file) {
read_csv(file, col_types = cols()) %>%
as_tibble() %>%
filter(!is.na(Ozone))
}
```
Now, instead of invoking a whole block of text, all you need to do is type a small reusable command. The function name speaks for itself, so you can recall what it does without having to mentally process all the details again.
```{r, eval = FALSE}
get_data("data.csv")
```
As with the data, we can write a function to fit a model,
```{r, eval = FALSE}
fit_model <- function(data) {
lm(Ozone ~ Temp, data) %>%
coefficients()
}
```
and another function to plot the model against the data.
```{r, eval = FALSE}
plot_model <- function(model, data) {
ggplot(data) +
geom_point(aes(x = Temp, y = Ozone)) +
geom_abline(intercept = model[1], slope = model[2]) +
theme_gray(24)
}
```
## Functions in pipelines
Without those functions, our pipeline in the [walkthrough chapter](#walkthrough) would look long, complicated, and difficult to digest.
```{r, eval = FALSE}
# _targets.R
library(targets)
library(tarchetypes)
tar_source()
tar_option_set(packages = c("tibble", "readr", "dplyr", "ggplot2"))
list(
tar_target(file, "data.csv", format = "file"),
tar_target(
data,
read_csv(file, col_types = cols()) %>%
filter(!is.na(Ozone))
),
tar_target(
model,
lm(Ozone ~ Temp, data) %>%
coefficients()
),
tar_target(
plot,
ggplot(data) +
geom_point(aes(x = Temp, y = Ozone)) +
geom_abline(intercept = model[1], slope = model[2]) +
theme_gray(24)
)
)
```
But if we write our functions in `R/functions.R` and `source()` them into the target script file (default: `_targets.R`) the pipeline becomes much easier to read. We can even condense out `raw_data` and `data` targets together without creating a large command.
```{r, eval = FALSE}
# _targets.R
library(targets)
library(tarchetypes)
tar_source()
tar_option_set(packages = c("tibble", "readr", "dplyr", "ggplot2"))
list(
tar_target(file, "data.csv", format = "file"),
tar_target(data, get_data(file)),
tar_target(model, fit_model(data)),
tar_target(plot, plot_model(model, data))
)
```
## Tracking changes
To help figure out which targets to rerun and which ones to skip, the `targets` package tracks changes to the functions you define. To track changes to a function, `targets` computes a [hash](https://en.wikipedia.org/wiki/Hash_function). This hash fingerprints the [deparsed](https://adv-r.hadley.nz/expressions.html#parsing) function (body and arguments) together with the hashes of all global functions and objects called that function. So if the function's body, arguments, or dependencies change nontrivially, that change will be detected.
This hashing system is not perfect. For example, functions created by `Rcpp::cppFunction()` do not show the state of the underlying C++ code. As a workaround, you can use a wrapper that inserts the C++ code into the R function body so `targets` can track it for meaningful changes.
```{r, eval = FALSE}
cpp_function <- function(code) {
out <- Rcpp::cppFunction(code)
body(out) <- rlang::call2("{", code, body(out))
out
}
your_function <- cpp_function(
"int your_function(int x, int y, int z) {
int sum = x + y + z;
return sum;
}"
)
```
Functions produced by `Vectorize()` and `purrr::safely()` suffer similar issues because the actual function code is in the closure of the function instead of the body. In addition, functions from packages are not automatically tracked, and [extra steps documented in the packages chapter](https://books.ropensci.org/targets/packages.html#package-based-invalidation) are required to enable this.
It is impossible to eliminate every edge case, so before running the pipeline, please [run the dependency graph](https://docs.ropensci.org/targets/reference/tar_visnetwork.html) and [other utilities](https://docs.ropensci.org/targets/reference/index.html#inspect) to check your understanding of the state of project.