| 1 |
--- |
| 2 |
title: "Unpacking Assignment" |
| 3 |
date: "`r Sys.Date()`" |
| 4 |
output: rmarkdown::html_vignette |
| 5 |
vignette: > |
| 6 |
%\VignetteIndexEntry{Unpacking Assignment} |
| 7 |
%\VignetteEngine{knitr::rmarkdown} |
| 8 |
%\VignetteEncoding{UTF-8} |
| 9 |
--- |
| 10 |
|
| 11 |
```{R, include = FALSE} |
| 12 |
knitr::opts_chunk$set(collapse = TRUE, comment = "#>") |
| 13 |
|
| 14 |
library(zeallot) |
| 15 |
``` |
| 16 |
|
| 17 |
## Getting Started |
| 18 |
The *zeallot* package defines an operator for *unpacking assignment*, sometimes |
| 19 |
called *parallel assignment* or *destructuring assignment* in other programming |
| 20 |
languages. The operator is written as `%<-%` and used like this. |
| 21 |
|
| 22 |
```{r} |
| 23 |
c(lat, lng) %<-% list(38.061944, -122.643889) |
| 24 |
``` |
| 25 |
|
| 26 |
The result is that the list is unpacked into its elements, |
| 27 |
and the elements are assigned to `lat` and `lng`. |
| 28 |
|
| 29 |
```{r} |
| 30 |
lat |
| 31 |
lng |
| 32 |
``` |
| 33 |
|
| 34 |
You can also unpack the elements of a vector. |
| 35 |
|
| 36 |
```{r} |
| 37 |
c(lat, lng) %<-% c(38.061944, -122.643889) |
| 38 |
lat |
| 39 |
lng |
| 40 |
``` |
| 41 |
|
| 42 |
You can unpack much longer structures, too, of course, such as the 6-part |
| 43 |
summary of a vector. |
| 44 |
|
| 45 |
```{r} |
| 46 |
c(min_wt, q1_wt, med_wt, mean_wt, q3_wt, max_wt) %<-% summary(mtcars$wt) |
| 47 |
min_wt |
| 48 |
q1_wt |
| 49 |
med_wt |
| 50 |
mean_wt |
| 51 |
q3_wt |
| 52 |
max_wt |
| 53 |
``` |
| 54 |
|
| 55 |
If the left-hand side and right-hand sides do not match, an error is raised. |
| 56 |
This guards against missing or unexpected values. |
| 57 |
|
| 58 |
```{r, error=TRUE} |
| 59 |
c(stg1, stg2, stg3) %<-% list("Moe", "Donald") |
| 60 |
``` |
| 61 |
|
| 62 |
```{r, error=TRUE} |
| 63 |
c(stg1, stg2, stg3) %<-% list("Moe", "Larry", "Curley", "Donald") |
| 64 |
``` |
| 65 |
|
| 66 |
### Unpacking a returned value |
| 67 |
A common use-case is when a function returns a list of values |
| 68 |
and you want to extract the individual values. |
| 69 |
In this example, the list of values returned by `coords_list()` is unpacked |
| 70 |
into the variables `lat` and `lng`. |
| 71 |
|
| 72 |
```{r} |
| 73 |
# |
| 74 |
# A function which returns a list of 2 numeric values. |
| 75 |
# |
| 76 |
coords_list <- function() { |
| 77 |
list(38.061944, -122.643889) |
| 78 |
} |
| 79 |
|
| 80 |
c(lat, lng) %<-% coords_list() |
| 81 |
lat |
| 82 |
lng |
| 83 |
``` |
| 84 |
|
| 85 |
In this next example, we call a function that returns a vector. |
| 86 |
|
| 87 |
```{r} |
| 88 |
# |
| 89 |
# Convert cartesian coordinates to polar |
| 90 |
# |
| 91 |
to_polar = function(x, y) { |
| 92 |
c(sqrt(x^2 + y^2), atan(y / x)) |
| 93 |
} |
| 94 |
|
| 95 |
c(radius, angle) %<-% to_polar(12, 5) |
| 96 |
radius |
| 97 |
angle |
| 98 |
``` |
| 99 |
|
| 100 |
### Example: Intercept and slope of regression |
| 101 |
You can directly unpack the coefficients of a simple linear regression |
| 102 |
into the intercept and slope. |
| 103 |
|
| 104 |
```{r} |
| 105 |
c(inter, slope) %<-% coef(lm(mpg ~ cyl, data = mtcars)) |
| 106 |
inter |
| 107 |
slope |
| 108 |
``` |
| 109 |
|
| 110 |
### Example: Unpacking the result of `safely` |
| 111 |
The *purrr* package includes the `safely` function. |
| 112 |
It wraps a given function to create a new, "safe" version of the original function. |
| 113 |
|
| 114 |
```{R, eval = require("purrr")} |
| 115 |
safe_log <- purrr::safely(log) |
| 116 |
``` |
| 117 |
|
| 118 |
The safe version returns a list of two items. The first item is the result of |
| 119 |
calling the original function, assuming no error occurred; or `NULL` if an error |
| 120 |
did occur. The second item is the error, if an error occurred; or `NULL` if no |
| 121 |
error occurred. Whether or not the original function would have thrown an error, |
| 122 |
the safe version will never throw an error. |
| 123 |
|
| 124 |
```{r, eval = require("purrr")} |
| 125 |
pair <- safe_log(10) |
| 126 |
pair$result |
| 127 |
pair$error |
| 128 |
``` |
| 129 |
|
| 130 |
```{r, eval = require("purrr")} |
| 131 |
pair <- safe_log("donald") |
| 132 |
pair$result |
| 133 |
pair$error |
| 134 |
``` |
| 135 |
|
| 136 |
You can tighten and clarify calls to the safe function by using `%<-%`. |
| 137 |
|
| 138 |
```{r, eval = require("purrr")} |
| 139 |
c(res, err) %<-% safe_log(10) |
| 140 |
res |
| 141 |
err |
| 142 |
``` |
| 143 |
|
| 144 |
## Unpacking a data frame |
| 145 |
A data frame is simply a list of columns, so the *zeallot* assignment does |
| 146 |
what you expect. It unpacks the data frame into individual columns. |
| 147 |
|
| 148 |
```{r} |
| 149 |
c(mpg=, cyl=, dist=, hp=) %<-% mtcars |
| 150 |
|
| 151 |
cyl |
| 152 |
``` |
| 153 |
|
| 154 |
### Example: List of data frames |
| 155 |
Bear in mind, a list of data frames is still just a list. The assignment |
| 156 |
will extract the list elements (which are data frames) but not unpack the data |
| 157 |
frames themselves. |
| 158 |
|
| 159 |
```{R} |
| 160 |
c(gear3, gear4, gear5) %<-% split(mtcars, ~ gear) |
| 161 |
|
| 162 |
head(gear3) |
| 163 |
|
| 164 |
head(gear4) |
| 165 |
|
| 166 |
gear5 |
| 167 |
``` |
| 168 |
|
| 169 |
The `%<-%` operator assigned four data frames to four variables, leaving the |
| 170 |
data frames intact. |
| 171 |
|
| 172 |
## Custom classes |
| 173 |
*zeallot* includes implementations of `destructure` for data frames and linear |
| 174 |
model summaries. However, because `destructure` is a generic function, you can |
| 175 |
define new implementations for custom classes. When defining a new |
| 176 |
implementation keep in mind the return value must be a list so the values are |
| 177 |
properly unpacked. |
| 178 |
|
| 179 |
## Trailing values: the "everything else" clause |
| 180 |
In some cases, you want the first few elements of a list or vector but do not |
| 181 |
care about the trailing elements. The `summary.lm` function, for example, |
| 182 |
returns a list of 11 values, and you may want only the first few. Fortunately, |
| 183 |
there is a way to capture those first few and say "don't worry about everything |
| 184 |
else". |
| 185 |
|
| 186 |
```{r} |
| 187 |
lm_mpg_cyl <- lm(mpg ~ cyl, data = mtcars) |
| 188 |
|
| 189 |
c(lmc_call, lmc_terms, lmc_residuals, ..rest) %<-% summary(lm_mpg_cyl) |
| 190 |
|
| 191 |
lmc_call |
| 192 |
|
| 193 |
lmc_terms |
| 194 |
|
| 195 |
head(lmc_residuals) |
| 196 |
``` |
| 197 |
|
| 198 |
The collector variable `rest` captures everything else. |
| 199 |
|
| 200 |
```{r} |
| 201 |
str(rest) |
| 202 |
``` |
| 203 |
|
| 204 |
Because `..rest` is prefixed with `..` a variable called `rest` is created |
| 205 |
for the trailing values of the list. |
| 206 |
|
| 207 |
## Leading values and middle values |
| 208 |
|
| 209 |
In addition to collecting trailing values, you can also collect initial values |
| 210 |
and assign specific remaining values. |
| 211 |
|
| 212 |
```{r} |
| 213 |
c(..skip, e, f) %<-% list(1, 2, 3, 4, 5) |
| 214 |
skip |
| 215 |
e |
| 216 |
f |
| 217 |
``` |
| 218 |
|
| 219 |
Or you can assign the first value, skip values, and then assign the last value. |
| 220 |
|
| 221 |
```{r} |
| 222 |
c(begin, ..middle, end) %<-% list(1, 2, 3, 4, 5) |
| 223 |
begin |
| 224 |
middle |
| 225 |
end |
| 226 |
``` |
| 227 |
|
| 228 |
## Skipped values: anonymous elements |
| 229 |
|
| 230 |
You can skip one or more values using a period (`.`) instead of a variable name. |
| 231 |
|
| 232 |
```{r} |
| 233 |
c(x, ., z) %<-% list(1, 2, 3) |
| 234 |
x |
| 235 |
z |
| 236 |
``` |
| 237 |
|
| 238 |
You can skip many values with the anonymous collector (`..`). |
| 239 |
|
| 240 |
```{r} |
| 241 |
c(begin, .., end) %<-% list("hello", "blah", list("blah"), "blah", "world!") |
| 242 |
begin |
| 243 |
end |
| 244 |
``` |
| 245 |
|
| 246 |
You can mix skips and collectors together to selectively keep and discard |
| 247 |
elements. |
| 248 |
|
| 249 |
```{r} |
| 250 |
c(begin, ., ..middle, end) %<-% list(1, 2, 3, 4, 5) |
| 251 |
begin |
| 252 |
middle |
| 253 |
end |
| 254 |
``` |
| 255 |
|
| 256 |
## Default values: handle missing values |
| 257 |
You can specify a default value for a left-hand side variable using `=`, similar |
| 258 |
to specifying the default value of a function argument. This comes in handy when |
| 259 |
the number of elements returned by a function cannot be guaranteed. `tail()` for |
| 260 |
example may return fewer elements than asked for. |
| 261 |
|
| 262 |
```{r} |
| 263 |
nums <- c(1, 2) |
| 264 |
c(x, y) %<-% tail(nums, 2) |
| 265 |
x |
| 266 |
y |
| 267 |
``` |
| 268 |
|
| 269 |
However, if we tried to get the last 3 elements an error would be raised because |
| 270 |
`tail(nums, 3)` still returns only 2 values. |
| 271 |
|
| 272 |
```{r, error = TRUE} |
| 273 |
c(x, y, z) %<-% tail(nums, 3) |
| 274 |
``` |
| 275 |
|
| 276 |
We can fix the problem by specifying a default value for `z`. |
| 277 |
|
| 278 |
```{r} |
| 279 |
c(x, y, z = NULL) %<-% tail(nums, 3) |
| 280 |
x |
| 281 |
y |
| 282 |
z |
| 283 |
``` |
| 284 |
|
| 285 |
## Swapping values |
| 286 |
A handy trick is swapping values without the use of a temporary variable. |
| 287 |
|
| 288 |
```{r} |
| 289 |
c(first, last) %<-% c("Ai", "Genly") |
| 290 |
first |
| 291 |
last |
| 292 |
|
| 293 |
c(first, last) %<-% c(last, first) |
| 294 |
first |
| 295 |
last |
| 296 |
``` |
| 297 |
|
| 298 |
or |
| 299 |
|
| 300 |
```{r} |
| 301 |
cat <- "meow" |
| 302 |
dog <- "bark" |
| 303 |
|
| 304 |
c(cat, dog, fish) %<-% c(dog, cat, dog) |
| 305 |
cat |
| 306 |
dog |
| 307 |
fish |
| 308 |
``` |