forked from storopoli/Linguagem-R
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4-Programacao_Funcional.Rmd
192 lines (145 loc) · 4.11 KB
/
4-Programacao_Funcional.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
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
---
title: "Programação Funcional"
description: "purrr e furrr"
author:
- name: Jose Storopoli
url: https://scholar.google.com/citations?user=xGU7H1QAAAAJ&hl=en
affiliation: UNINOVE
affiliation_url: https://www.uninove.br
orcid_id: 0000-0002-0559-5176
date: April 16, 2021
citation_url: https://storopoli.io/Linguagem-R/4-Programacao_Funcional.html
slug: storopoli2021programacaofuncionalR
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
<link rel="stylesheet" href="https://cdn.rawgit.com/jpswalsh/academicons/master/css/academicons.min.css"/>
```{r map-frosting, echo=FALSE, fig.align='center', fig.cap='Programação Funcional'}
knitr::include_graphics("images/map_frosting.png")
```
[`{purrr}`](https://purrr.tidyverse.org) tem a seguinte lógica:
Ao invés de:
```r
for (i in 1:n) {
output[[i]] <- f(input[[i]])
}
```
Você faz:
```r
library(purrr)
list %>% map(f) # ou map(list, f)
```
```{r exemplo-rnorm}
library(purrr)
1L:10L %>% map(rnorm, 5, 10)
```
* `map()` — sempre retorna uma `list`
* `map_lgl()`, `map_int()`, `map_dbl()` e `map_chr()` — retornam um vetor do tipo desejado (conversão implícita)
* `map_dfr()` e `map_dfc()` — retornaram um `data.frame` concatenando colunas (`c`) ou linhas (`r`)
* `walk()` — usado para efeitos colaterais (side-effects)
Além disso temos o `map2*` (2 listas de inputs) e o `pmap*` (lista de vetores de inputs, pode ser um `data.frame`) para múltiplos inputs.
## `map_*()`
Conversão implícita
```{r map_dbl}
1L:10L %>%
map(rnorm) %>%
map_dbl(mean) # igual a map_dbl(~mean(.x))
```
## Professor, e a `~`?
O tio `~` (em inglês é tilde) ele funciona quando você precisa especificar funções e argumentos mais complexos:
```{r map-tilde}
c("meu", "microfone", "está", "aberto") %>% # vire um vetor de c("meuprefixo_meu", ...)
map_chr(~paste0("meuprefixo_", .x))
```
```{r map-ggplot}
library(ggplot2)
c("hp", "wt", "qsec") %>%
map(~mtcars %>%
ggplot(aes_string(.x, "mpg")) +
geom_point() +
geom_smooth())
```
Agora é um bom momento para introduzir o `purrr::walk`
* `walk()` — usado para efeitos colaterais (*side-effects*)
```{r purrr-walk}
c("hp", "wt", "qsec") %>%
walk(~ {p <- mtcars %>%
ggplot(aes_string(.x, "mpg")) +
geom_point() +
geom_smooth()
print(p)})
```
```{r purrr-walk2}
y <- c("mpg", "cyl", "gear")
c("hp", "wt", "qsec") %>%
walk2(y, ~{p <- mtcars %>%
ggplot(aes_string(.x, .y)) +
geom_point() +
geom_smooth()
print(p)})
```
Agora o `purrr::pwalk()`
```{r purrr-pwalk}
x <- c("hp", "wt", "qsec")
y <- c("mpg", "cyl", "gear")
z <- c("vs", "am", "cyl")
list_v <- list(x, y, z)
list_v %>%
pwalk(~{p <- mtcars %>%
ggplot(aes_string(..1, ..2, colour = ..3)) + # e continua ..4 ..5 ..6
geom_point() +
geom_smooth()
print(p)})
```
Até dá para "knitar" vários markdowns
```r
c("arquivo1.Rmd", "arquivo2.Rmd", ...) %>% # ou fs::dir_ls(glob = "*.Rmd") lê todo o diretório
walk(~knitr::render(.x,
output_format = "html_document",
output_dir = "relatorios/"))
```
## MOAH POWER! `{furrr}`
`{purrr}` é single-thread então vamos usar o [`{furrr}`](https://furrr.futureverse.org).
Para usar é muito fácil! Ao invés de:
* `map()`
* `map2()`
* `pmap()`
* `walk()`
Use:
* `future_map()`
* `future_map2()`
* `future_pmap()`
* `future_walk()`
```{r purrr-sleep}
seq_len(8) %>%
walk(~{
Sys.sleep(1)
print("Oi")})
```
Agora com o `{furrr}`:
```{r furrr}
library(furrr)
plan(multisession) # ou coloque no `.Rprofile` `options(Ncpus = parallel::detectCores())` e `options(mc.cores = parallel::detectCores())`
```
```{r furrr-sleep}
seq_len(8) %>%
future_walk(~{
Sys.sleep(1)
print("Oi")},
.progress = TRUE)
```
Se for mexer com coisas aleatórias é importante usar o argumento:
* `.options = furrr_options(seed = TRUE)`
```{r furrr-random}
1L:10L %>% future_map(rnorm)
```
```{r furrr-random2}
1L:10L %>%
future_map(rnorm,
.options = furrr_options(seed = TRUE))
```
## Ambiente
```{r sessionInfo}
sessionInfo()
```