Upcoming SlideShare
×

# Functional Programming in R

3,036 views

Published on

Presentation I gave at the Manchester R user group on 02/05/2013

Published in: Technology
6 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total views
3,036
On SlideShare
0
From Embeds
0
Number of Embeds
25
Actions
Shares
0
99
0
Likes
6
Embeds 0
No embeds

No notes for slide

### Functional Programming in R

1. 1. What is functional programming?Functional programming in RWrap-upFunctional Programming in RDavid Springate@datajujitsuDavid Springate Functional Programming in R
2. 2. What is functional programming?Functional programming in RWrap-upOutline1 What is functional programming?2 Elements of functional programming3 Functional Programming in R4 A Functional-style generic bootstrap5 Wrap-up and further readingDavid Springate Functional Programming in R
3. 3. What is functional programming?Functional programming in RWrap-upWhat is functional programming?David Springate Functional Programming in R
4. 4. What is functional programming?Functional programming in RWrap-upProgramming metaphysicsPrograms are representations of reality in a computerThere are diﬀerent ways to represent reality. . .David Springate Functional Programming in R
5. 5. What is functional programming?Functional programming in RWrap-upOOP / imperative metaphysicsC, Python, Java etc.Everything is an object with state and behaviourA river is an object withvarious attributes boundto it:Flow rateDepthPollution levelsSalinityDavid Springate Functional Programming in R
6. 6. What is functional programming?Functional programming in RWrap-upFunctional MetaphysicsNo man ever steps in the same river twice, for it’snot the same river and he’s not the same man. -HeraclitusLisp, Haskell, F#, Clojure etc.Things are collections of ﬁxed values whichgo through processes (functions) over timeDavid Springate Functional Programming in R
7. 7. What is functional programming?Functional programming in RWrap-upElements of Functional Programming1 Functions as ﬁrst class citizens2 Vectorised / declarative expressions3 “Pure” functions - No side eﬀects4 Anonymous functions5 Immutability6 RecursionDavid Springate Functional Programming in R
8. 8. What is functional programming?Functional programming in RWrap-upFunctional programming in RDavid Springate Functional Programming in R
9. 9. What is functional programming?Functional programming in RWrap-upR GenealogySSchemeDavid Springate Functional Programming in R
10. 10. What is functional programming?Functional programming in RWrap-upR is a strongly functional language. . . everything is a function call!> 1 + 2## [1] 3. . . is the same as. . .> ‘+‘(1, 2)## [1] 3David Springate Functional Programming in R
11. 11. What is functional programming?Functional programming in RWrap-upR is a strongly functional language. . . everything is a function call!> 1:10## [1] 1 2 3 4 5 6 7 8 9 10. . . is the same as. . .> ‘:‘(1, 10)## [1] 1 2 3 4 5 6 7 8 9 10David Springate Functional Programming in R
12. 12. What is functional programming?Functional programming in RWrap-upVectorised functionsAre functions that operate on vectors/matrices/dataframes as wellas on single numbersOften much faster than looping over a vectorHigher level - less to debug!Very deep in the languageDavid Springate Functional Programming in R
13. 13. What is functional programming?Functional programming in RWrap-upVectorised functionsGet all even numbers up to 200000> # C style vector allocation:> x <- c()> for(i in 1:200000){+ if(i %% 2 == 0){+ x <- c(x, i)+ }+ }## user system elapsed## 9.86 0.00 9.88David Springate Functional Programming in R
14. 14. What is functional programming?Functional programming in RWrap-upVectorised functionsGet all even numbers up to 200000> # FP style vectorised operation> a <- 1:200000> x <- a[a %% 2 == 0]## user system elapsed## 0.01 0.00 0.01David Springate Functional Programming in R
15. 15. What is functional programming?Functional programming in RWrap-upVectorised functionsMost built-in functions are vectorised:> # e.g.> paste()> colMeans()> rowSums()> log()> sqrt()> x > y> is.na()> ifelse()> rnorm() # etc. etc.David Springate Functional Programming in R
16. 16. What is functional programming?Functional programming in RWrap-upHigher-order functions. . . Are functions that operate on all elements of a collection(vector/list/vector/matrix/dataframe)Function to be applied to each element in turnIn[1] In[2] In[3] In[5]In[4]Out[1] Out[2] Out[3] Out[5]Out[4]InputcollectionOutputcollectionDavid Springate Functional Programming in R
17. 17. What is functional programming?Functional programming in RWrap-upHigher-order functionsYou just need to think about what goes in and what you want tocome out:lapply : Any collection -> FUNCTION -> listDavid Springate Functional Programming in R
18. 18. What is functional programming?Functional programming in RWrap-upHigher-order functionsYou just need to think about what goes in and what you want tocome out:lapply : Any collection -> FUNCTION -> listsapply : Any collection -> FUNCTION -> matrix/vectorDavid Springate Functional Programming in R
19. 19. What is functional programming?Functional programming in RWrap-upHigher-order functionsYou just need to think about what goes in and what you want tocome out:lapply : Any collection -> FUNCTION -> listsapply : Any collection -> FUNCTION -> matrix/vectorapply : Matrix/dataframe + margin -> FUNCTION ->matrix/vectorDavid Springate Functional Programming in R
20. 20. What is functional programming?Functional programming in RWrap-upHigher-order functionsYou just need to think about what goes in and what you want tocome out:lapply : Any collection -> FUNCTION -> listsapply : Any collection -> FUNCTION -> matrix/vectorapply : Matrix/dataframe + margin -> FUNCTION ->matrix/vectorReduce : Any collection -> FUNCTION -> single elementDavid Springate Functional Programming in R
21. 21. What is functional programming?Functional programming in RWrap-upClosuresAn object is data with functions. A closure is a function with data.- John D CookFunction data1ReturnsNew functionenclosing datadatadata2Arguments to functiondata2Can build functions thatreturn new functions:Useful if some workonly needs to be doneonce, when thefunction is generatedGreat for optimisationand randomisationproblemsDavid Springate Functional Programming in R
22. 22. What is functional programming?Functional programming in RWrap-upAn FP-style Bootstrapping functionA Generic function to sample linear models with replacementIllustrates:Functions returning new functionsHigher-order functionsAnonymous functionsVectorised functionsWill test using the iris data: data(iris)c.f. a non-FP version of the same functionDavid Springate Functional Programming in R
23. 23. What is functional programming?Functional programming in RWrap-upAn FP-style Bootstrapping functionboot_lm <- function(formula, data, ...){function(){lm(formula=formula,data=data[sample(nrow(data), replace=TRUE),], ...)}}iris_boot <- boot_lm(Sepal.Length ~ Petal.Length, iris)bstrap <- sapply(X=1:1000,FUN=function(x) iris_boot()\$coef)David Springate Functional Programming in R
24. 24. What is functional programming?Functional programming in RWrap-upAn FP-style Bootstrapping functionapply(bstrap, MARGIN=1, FUN=quantile,probs=c(0.025, 0.5, 0.975))## (Intercept) Petal.Length## 2.5% 4.155 0.3696## 50% 4.314 0.4072## 97.5% 4.458 0.4455David Springate Functional Programming in R
25. 25. What is functional programming?Functional programming in RWrap-upA Non-FP-style Bootstrapping functionboot_lm_nf <- function(d, form, iters, output, ...){for(i in 1:iters){x <- lm(formula=form,data=d[sample(nrow(d),replace = TRUE),], ...)[[output]]if(i == 1){bootstrap <- matrix(data=NA, nrow=iters,ncol=length(x),dimnames=list(NULL,names(x)))bootstrap[i,] <- x} else bootstrap[i,] <- x}bootstrap}David Springate Functional Programming in R
26. 26. What is functional programming?Functional programming in RWrap-upA Non-FP-style Bootstrapping functionbstrap2 <- boot_lm_nf(d=iris,form=Sepal.Length ~ Petal.Length,iters=1000, output="coefficients")CIs <- c(0.025, 0.5, 0.975)cbind( "(Intercept)"=quantile(bstrap2[,1],probs = CIs),"Petal.Length"=quantile(bstrap2[,2],probs = CIs))## (Intercept) Petal.Length## 2.5% 4.167 0.3711## 50% 4.309 0.4093## 97.5% 4.447 0.4460David Springate Functional Programming in R
27. 27. What is functional programming?Functional programming in RWrap-upWrap-upDavid Springate Functional Programming in R
28. 28. What is functional programming?Functional programming in RWrap-upAdvantages of Functional ProgrammingFunctional programming in R isMore conciseOften fasterEasier to read and debugMore elegantHigher levelTruer to the language!. . . than non-fpDavid Springate Functional Programming in R
29. 29. What is functional programming?Functional programming in RWrap-upFurther readingFunctional Programmingmitpress.mit.edu/sicpFunctional programming in Rgithub.com/hadley/devtools/wikiwww.burns-stat.com/pages/Tutor/R_inferno.pdfVectorisationProgramming language metaphysicshttp://www.infoq.com/presentations/Are-We-There-Yet-Rich-HickeyDavid Springate Functional Programming in R
30. 30. What is functional programming?Functional programming in RWrap-upThank yougithub.com/DASpringatelinkedin.com/in/daspringate/@datajujitsudaspringate@gmail. . . Any questions?David Springate Functional Programming in R