Why cleaner code?

Intermediate Functional Programming with purrr

Colin Fay

Data Scientist & R Hacker

Where's Waldo?

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)
Intermediate Functional Programming with purrr

Finding Waldo

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)
Intermediate Functional Programming with purrr

What is clean code?

Clean code is:

  • Light
  • Readable
  • Interpretable
  • Maintainable
Intermediate Functional Programming with purrr

compose()

Composing functions:

library(purrr)

rounded_mean <- compose(round, mean)
rounded_mean(1:2811)
1406
Intermediate Functional Programming with purrr

Composing cleaner code

# FROM
round(mean(1:10))
round(mean(1:100))
round(mean(1:1000))
round(mean(1:10000))
#TO
round(median(1:10))
round(median(1:100))
round(median(1:1000))
round(median(1:10000))

-> 4 changes

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

-> 1 change

Intermediate Functional Programming with purrr

Let's practice!

Intermediate Functional Programming with purrr

Preparing Video For Download...