Functional programming in R

Intermediate Functional Programming with purrr

Colin Fay

Data Scientist & R Hacker at ThinkR

About computation in R

"To understand computations in R, two slogans are helpful:

- Everything that exists is an object.

- Everything that happens is a function call."    -John Chambers

class(`+`)
"function"
class(`<-`)
"function"
Intermediate Functional Programming with purrr

R as a functional programming language

Functions can be

  • manipulated

  • stored in a variable

  • lambda

 

  • stored in a list

  • arguments of a function

  • returned by a function

Intermediate Functional Programming with purrr

About "pure functions"

In a pure function:

  • output only depends on input

  • no "side-effect"

# Output depends only on inputs
# No side effect
sum(1:10)
55
mean(1:100)
50.5
Intermediate Functional Programming with purrr

Impure functions are useful

Impure functions:

  • Depend on environment

  • Have "side-effects"

# Outputs depends of environment 
Sys.Date()
"2018-10-04"
# Side effect only
write.csv(iris, "iris.csv")
Intermediate Functional Programming with purrr

Read more about functional programming

Intermediate Functional Programming with purrr

Let's practice!

Intermediate Functional Programming with purrr

Preparing Video For Download...