Waarom schonere code?

Gevorderd functioneel programmeren met purrr

Colin Fay

Data Scientist & R Hacker

Waar is Wally?

library(broom)
library(dplyr)
lm(Sepal.Length ~ Species, data=iris) %>% tidy() %>% filter(p.value < 0.05)
lm(Pepal.Length ~ Species, data=iris) %>% tidy() %>% filter(p.value < 0.05)
lm(Sepal.Width ~ Species, data=iris) %>% tidy() %>% filter(p.value < 0.05)
lm(Sepal.Length ~ Species, data=iris) %>% tidy() %>% ilter(p.value < 0.05)
Gevorderd functioneel programmeren met purrr

Wally vinden

library(purrr)
tidy_iris_lm <- compose(
  as_mapper(~ filter(.x, p.value < 0.05)), 
  tidy, 
  partial(lm, data=iris, na.action = na.fail)
)

list( Petal.Length ~ Petal.Width, Petal.Width ~ Sepal.Width, Sepal.Width ~ Sepal.Length ) %>% map(tidy_iris_lm)
Gevorderd functioneel programmeren met purrr

Wat is schone code?

Schone code is:

  • Licht
  • Leesbaar
  • Interpreteerbaar
  • Onderhoudbaar
Gevorderd functioneel programmeren met purrr

compose()

Functies componeren:

library(purrr)

rounded_mean <- compose(round, mean)
rounded_mean(1:2811)
1406
Gevorderd functioneel programmeren met purrr

Schonere code componeren

# VAN
round(mean(1:10))
round(mean(1:100))
round(mean(1:1000))
round(mean(1:10000))
# NAAR
round(median(1:10))
round(median(1:100))
round(median(1:1000))
round(median(1:10000))

-> 4 wijzigingen

# VAN
my_stats <- compose(round, mean)
my_stats(1:10)
my_stats(1:100)
my_stats(1:1000)
my_stats(1:10000)
# NAAR
my_stats <- compose(round, median)
my_stats(1:10)
my_stats(1:100)
my_stats(1:1000)
my_stats(1:10000)

-> 1 wijziging

Gevorderd functioneel programmeren met purrr

Laten we oefenen!

Gevorderd functioneel programmeren met purrr

Preparing Video For Download...