Repository navigation
Expand file tree
/
Copy pathREADME.Rmd
More file actions
executable file
·77 lines (59 loc) · 2.1 KB
/
Copy pathREADME.Rmd
File metadata and controls
executable file
·77 lines (59 loc) · 2.1 KB
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
---
output: github_document
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
```{r, echo = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "README-"
)
```
## Introduction
We all know R is not the place to write for-loops, but some of us really, really like them. This package is inspired by Python's list comprehensions that make it possible to write for-loops in only a few keystrokes. Note that this package makes for-loops faster to write, not faster to run.
You can install the most recent version of `yuck` from GitHub:
```{r, eval = FALSE}
devtools::install_github("tpq/yuck")
library(yuck)
```
```{r, echo = FALSE}
library(yuck)
```
## Single loop comprehensions
A list comprehension allows a user to step through a for-loop and save each result in one line of code, similar to what `lapply` does. The `yuck` package introduces the `:=` operator to trigger a list comprehension by computing the expression on the right and saving it to the value on the left.
```{r}
a := for(i in 1:5) i^2
a
```
## Nested loop comprehensions
The `yuck` package allows for nested loop comprehensions.
```{r}
a := for(i in 1:5) for(j in 1:7) (i - 1)^2 + (j - 1)^2
matrix(a, 7, 5)
```
## Use cases
The examples above are arbitrary and the problems presented have better (i.e., vectorized) solutions. Rather, the advantage of `yuck` comes from its use in combination with others tools. For example, we could use `yuck` to iterate across multiple machine learning parameters, models, and predictions. We can also combine `yuck` with `magrittr` to comprehend pipes.
```{r}
library(e1071)
library(magrittr)
data(iris)
groups <- split(sample(1:nrow(iris)), 1:2)
train <- iris[groups[[1]],]
test <- iris[groups[[2]],]
confs := for(kernel in c("linear", "radial", "polynomial"))
svm(Species ~ ., train, kernel = kernel) %>%
predict(test) %>% table(test$Species)
confs
```
I like using `yuck` to measure CPU time and RAM overhead.
```{r}
library(peakRAM)
times := for(i in c(1e5, 1e6, 1e7)) data.frame(i,
peakRAM(
function() 1:i,
1:i,
1:i + 1:i,
1:i * 2
))[,-3]
times
```