SlideShare a Scribd company logo
Functional Programming in R 
A Pragmatic Introduction 
Soumendra Prasad Dhanee 
Data Scientist 
.com 
18th October, 2014 
8th November, 2014 
(delivered at R Meetup, Mumbai) 
Soumendra Prasad Dhanee Functional Programming in R Slide 1/51
1 Introduction 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
2 More about functions 
Problem 2 
Anonymous Functions 
Problem 3 
3 Applicative Programming 
Map 
mapply 
Filter 
Negate 
4 Closure 
Soumendra Prasad Dhanee Functional Programming in R Slide 2/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Overview 
We'll start by reviewing basics 
We'll see the ideas at action
rst (by solving problems) and 
abstractions later 
We'll digress a lot 
Soumendra Prasad Dhanee Functional Programming in R Slide 3/51
Next ... 
1 Introduction 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
2 More about functions 
Problem 2 
Anonymous Functions 
Problem 3 
3 Applicative Programming 
Map 
mapply 
Filter 
Negate 
4 Closure 
Soumendra Prasad Dhanee Functional Programming in R Slide 4/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Writing a function in R 
func t ionname < f u n c t i o n ( arg1 , arg2 , . . . ) f 1 
e x p r e s s i o n s  2 
[ r e t u r n (e x p r e s s i o n ) ] 3 
g 4 
return() is optional 
last statement of the function body is returned by default 
Soumendra Prasad Dhanee Functional Programming in R Slide 5/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Example of a Function 
s q u a r e . o f  f u n c t i o n ( x ) f 1 
x*x 2 
g 3 
Call the function 
s q u a r e . o f ( 4 ) 1 
y  s q u a r e . o f ( x=4) 2 
s q u a r e . o f ( z=4) 3 
Soumendra Prasad Dhanee Functional Programming in R Slide 6/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
More on Functions 
Arguments of R functions can be either required or optional, 
indicated by syntax 
Required arguments have no default value 
Optional arguments are de
ned to have a default value 
Soumendra Prasad Dhanee Functional Programming in R Slide 7/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
More on Functions - Example 
add  f u n c t i o n ( x , y = 2) f 1 
x+y 2 
g 3 
add ( 3 ) 1 
add ( 3 , 2 ) 2 
add ( x=3) 3 
add ( x=3, y=2) 4 
add ( y=2) 5 
add ( , 3) 6 
Soumendra Prasad Dhanee Functional Programming in R Slide 8/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Example - Computing Power I 
Write a function that computes the kth power of an argument x, 
using one default argument, and one optional argument, i.e. an 
argument that has a default value. 
We'll be coming back to this function later on. 
Soumendra Prasad Dhanee Functional Programming in R Slide 9/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Example - Computing Power II 
power  f u n c t i o n ( x , k=2) x^k 1 
Soumendra Prasad Dhanee Functional Programming in R Slide 10/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
The apply family of functions 
lapply(X, FUN, ...) 
returns a list of the same length as X, each element of which is 
the result of applying FUN to the corresponding element of X 
sapply(X, FUN, ...) 
a user-friendly version of lapply by default returning a vector 
or matrix if appropriate 
Read the Documentation 
Soumendra Prasad Dhanee Functional Programming in R Slide 11/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Vectorized Functions 
... functions that operate on vectors or matrices or dataframes. 
Often much faster than looping over a vector, often use 
.Internal or .Primitive 
Higher abstraction - less code to write, less to debug 
Soumendra Prasad Dhanee Functional Programming in R Slide 12/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
.Internal and .Primitive - I 
log 
## function (x, base = exp(1)) .Primitive(log) 
paste 
## function (..., sep =  , collapse = NULL) 
## .Internal(paste(list(...), sep, collapse)) 
## bytecode: 0x1f8a2c8 
## environment: namespace:base 
Soumendra Prasad Dhanee Functional Programming in R Slide 13/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
.Internal and .Primitive - II 
colMeans 
## function (x, na.rm = FALSE, dims = 1L) 
## { 
## if (is.data.frame(x)) 
## x - as.matrix(x) 
## if (!is.array(x) || length(dn - dim(x))  2L) 
## stop(
x
 must be an array of at least two dimensions) 
## if (dims  1L || dims  length(dn) - 1L) 
## stop(invalid 
dims
) 
## n - prod(dn[1L:dims]) 
## dn - dn[-(1L:dims)] 
## z - if (is.complex(x)) 
## .Internal(colMeans(Re(x), n, prod(dn), na.rm)) + Soumendra Prasad Dhanee Functional Programming in R Slide 14/51 
## .Internal(colMeans(Im(x), n, prod(dn), na.rm))
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Examples of Vectorized Functions 
ifelse() 
is.na() 
log() 
sqrt() 
rnorm() 
colMeans() 
rowSums() 
x  y 
x == y 
!x 
Soumendra Prasad Dhanee Functional Programming in R Slide 15/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Primality Testing I 
Given a number, decide if it is a prime or not. 
Hint 1 : min(x) gives the lowest element of vector x 
min(c(2, 1, 3)) 
## [1] 1 
Soumendra Prasad Dhanee Functional Programming in R Slide 16/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Primality Testing II 
min ( x%%( 2 : ( x1) ) )0 1 
The Deconstruction 
2 : ( x1) 1 
x%%( 2 : ( x1) ) 2 
min ( x%%( 2 : ( x1) ) )0 3 
Soumendra Prasad Dhanee Functional Programming in R Slide 17/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Lists of functions 
x - 1:10 
funs - list( 
sum = sum, 
mean = mean, 
median = median 
) 
sapply(funs, function(f) f(x)) 
## sum mean median 
## 55.0 5.5 5.5 
Soumendra Prasad Dhanee Functional Programming in R Slide 18/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Let's get started 
Problem 1 
Input 
A numeric vector (1:200000) 
Output 
A vector containing the even numbers in the input 
vector, listed in the order they appeared in the input 
vector 
Soumendra Prasad Dhanee Functional Programming in R Slide 19/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Solution - for loop I 
Solution using for loop 
x  1:200000 1 
ans  l o g i c a l (200000) 2 
f o r ( i i n x ) 3 
f 4 
i f ( i%%2==0) f ans [ i ] = TRUE g e l s e f 5 
ans [ i ] = FALSE g 6 
g 7 
x [ ans ] 8 
## user system elapsed 
## 0.542 0.005 0.546 
Soumendra Prasad Dhanee Functional Programming in R Slide 20/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Solution - for loop II 
Solution using for loop 
x  1:200000 1 
ans  c ( ) 2 
f o r ( i i n x ) 3 
f 4 
i f ( i%%2==0) f ans [ i ] = TRUE g e l s e f 5 
ans [ i ] = FALSE g 6 
g 7 
x [ ans ] 8 
## user system elapsed 
## 56.511 2.631 59.333 
Soumendra Prasad Dhanee Functional Programming in R Slide 21/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Solution - vectorized functions 
Solution using vectorized functions 
x  1:200000 1 
ans  x%%2==0 2 
x [ ans ] 3 
## user system elapsed 
## 0.013 0.000 0.013 
Soumendra Prasad Dhanee Functional Programming in R Slide 22/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
Solution - higher-order functions 
Solution using higher-order functions 
x  1:200000 1 
ans  s a p p l y ( x , f u n c t i o n ( i ) i%%2==0) 2 
x [ ans ] 3 
## user system elapsed 
## 0.554 0.011 0.566 
Soumendra Prasad Dhanee Functional Programming in R Slide 23/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
What are higher-order functions? 
Higher-order Functions 
A higher-order function (also functional form, functional or 
functor) is a function that does at least one of the following: 
takes one or more functions as an input 
outputs a function 
-source - Wikipedia 
Soumendra Prasad Dhanee Functional Programming in R Slide 24/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
An example 
sapply 
sapply(X, FUN, ...) 
Soumendra Prasad Dhanee Functional Programming in R Slide 25/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
What are
rst-class functions? 
First-class Functions 
First-class functions are functions that can be treated like any 
other piece of data ... 
can be stored in a variable 
can be stored in a list 
can be stored in an object 
can be passed to other functions 
can be returned from other functions 
... just like any other piece of data. 
Soumendra Prasad Dhanee Functional Programming in R Slide 26/51
Next ... 
1 Introduction 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
2 More about functions 
Problem 2 
Anonymous Functions 
Problem 3 
3 Applicative Programming 
Map 
mapply 
Filter 
Negate 
4 Closure 
Soumendra Prasad Dhanee Functional Programming in R Slide 27/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Problem 2 
Anonymous Functions 
Problem 3 
Rounding o 
Problem 2a 
Input 
A numeric vector (rnorm(100, 0, 1)) 
Output 
A vector containing all the numbers in the input vector 
rounded to the nearest integer 
Soumendra Prasad Dhanee Functional Programming in R Slide 28/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Problem 2 
Anonymous Functions 
Problem 3 
Solution 2a - Rounding o 
Solution using sapply 
s a p p l y ( rnorm (100 , 0 , 1) , round ) 1 
Soumendra Prasad Dhanee Functional Programming in R Slide 29/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Problem 2 
Anonymous Functions 
Problem 3 
Rounding o 
Problem 2b 
Input 
A numeric vector (rnorm(100, 0, 1)) 
Output 
A vector containing all the numbers in the input vector 
rounded to two decimal places 
Soumendra Prasad Dhanee Functional Programming in R Slide 30/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Problem 2 
Anonymous Functions 
Problem 3 
Solution 2b - Rounding o 
Solution using sapply 
s a p p l y ( rnorm (100 , 0 , 1) , f u n c t i o n ( x ) round ( x , 2) ) 1 
Soumendra Prasad Dhanee Functional Programming in R Slide 31/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Problem 2 
Anonymous Functions 
Problem 3 
Anonymous Functions 
Anonymous Functions 
Anonymous function is a function that is not bound to an 
identi
er. 
source - Wikipedia 
Soumendra Prasad Dhanee Functional Programming in R Slide 32/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Problem 2 
Anonymous Functions 
Problem 3 
Acting on Matrices 
Problem 3 
Input 
A 3-by-3 matrix (matrix(1:9, ncol=3)) 
Output 
Add 1 to row 1, 4 to row 2, 7 to row 3 
Soumendra Prasad Dhanee Functional Programming in R Slide 33/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Problem 2 
Anonymous Functions 
Problem 3 
Solution 3 - Matrix Addition 
Solution using sweep 
m  ma t r i x ( 1 : 9 , n c o l=3) 1 
sweep (m, 1 , c ( 1 , 4 , 7) , + ) 2 
## [,1] [,2] [,3] 
## [1,] 2 5 8 
## [2,] 6 9 12 
## [3,] 10 13 16 
Soumendra Prasad Dhanee Functional Programming in R Slide 34/51
Next ... 
1 Introduction 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
2 More about functions 
Problem 2 
Anonymous Functions 
Problem 3 
3 Applicative Programming 
Map 
mapply 
Filter 
Negate 
4 Closure 
Soumendra Prasad Dhanee Functional Programming in R Slide 35/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Map 
mapply 
Filter 
Negate 
Applicative Programming 
Calling by function B of function A, where function A was 
originally supplied to function B as an argument. 
Examples 
map 
reduce (fold)
lter 
Soumendra Prasad Dhanee Functional Programming in R Slide 36/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Map 
mapply 
Filter 
Negate 
Map 
Map(f, x, ...) 
1 
f u n c t i o n ( f , . . . ) 2 
f 3 
f  match . fun ( f ) 4 
mapply (FUN = f , . . . , SIMPLIFY = FALSE) 5 
g 6 
by t e code : 0 x402ad90 7 
env i ronment : namespace : base 8 
Soumendra Prasad Dhanee Functional Programming in R Slide 37/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Map 
mapply 
Filter 
Negate 
mapply 
mapply is a multivariate version of sapply. 
mapply ( rep , 1 : 4 , 4 : 1 ) 1 
2 
mapply ( rep , t ime s = 1 : 4 , x = 4 : 1 ) 3 
4 
mapply ( rep , x = 1 : 4 , t ime s = 4 : 1 ) 5 
Soumendra Prasad Dhanee Functional Programming in R Slide 38/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Map 
mapply 
Filter 
Negate 
Filter I 
Choose all the even numbers. 
F i l t e r ( f u n c t i o n ( x ) x%%2 , 1:200000) 1 
## user system elapsed 
## 0.419 0.004 0.424 
Soumendra Prasad Dhanee Functional Programming in R Slide 39/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Map 
mapply 
Filter 
Negate 
Filter II 
The previous solution was wrong. 
Now what is the output of the following - 
F i l t e r ( c (T, F) , 1:200000) 1 
Soumendra Prasad Dhanee Functional Programming in R Slide 40/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Map 
mapply 
Filter 
Negate 
Filter III 
f u n c t i o n ( f , x ) 1 
f 2 
i n d  as . l o g i c a l ( u n l i s t ( l a p p l y ( x , f ) ) ) 3 
x [ ! i s . na ( i n d )  i n d ] 4 
g 5 
by t e code : 0 x4f87f00 6 
env i ronment : namespace : base 7 
Soumendra Prasad Dhanee Functional Programming in R Slide 41/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Map 
mapply 
Filter 
Negate 
Negate I 
What is the outcome? 
Negate ( c (T, F) , 1 : 1 0 ) 1 
Soumendra Prasad Dhanee Functional Programming in R Slide 42/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Map 
mapply 
Filter 
Negate 
Negate II 
What is the outcome? 
F i l t e r ( Negate ( f u n c t i o n ( x ) x%%2) , 1 : 1 0 ) 1 
Soumendra Prasad Dhanee Functional Programming in R Slide 43/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Map 
mapply 
Filter 
Negate 
Negate III 
f u n c t i o n ( f ) 1 
f 2 
f  match . fun ( f ) 3 
f u n c t i o n ( . . . ) ! f ( . . . ) 4 
g 5 
by t e code : 0 x4e9c250 6 
env i ronment : namespace : base 7 
Soumendra Prasad Dhanee Functional Programming in R Slide 44/51
Next ... 
1 Introduction 
Getting Started 
Vectorization 
Vectorization in Practice 
Problem 1 
Higher-order Functions 
First-class Functions 
2 More about functions 
Problem 2 
Anonymous Functions 
Problem 3 
3 Applicative Programming 
Map 
mapply 
Filter 
Negate 
4 Closure 
Soumendra Prasad Dhanee Functional Programming in R Slide 45/51
Introduction 
More about functions 
Applicative Programming 
Closure 
Computing Power Revisited 
Write a function that computes the kth power of an argument x, 
using one default argument, and one optional argument, i.e. an 
argument that has a default value. 
power  f u n c t i o n ( x , k=2) f 1 
x^k 2 
g 3 
Soumendra Prasad Dhanee Functional Programming in R Slide 46/51
Ad

More Related Content

What's hot (20)

Data manipulation on r
Data manipulation on rData manipulation on r
Data manipulation on r
Abhik Seal
 
R programming slides
R  programming slidesR  programming slides
R programming slides
Pankaj Saini
 
Introduction to R Programming
Introduction to R ProgrammingIntroduction to R Programming
Introduction to R Programming
izahn
 
Descriptive Statistics with R
Descriptive Statistics with RDescriptive Statistics with R
Descriptive Statistics with R
Kazuki Yoshida
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
Avjinder (Avi) Kaler
 
Introduction to R and R Studio
Introduction to R and R StudioIntroduction to R and R Studio
Introduction to R and R Studio
Rupak Roy
 
Unit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptxUnit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptx
Malla Reddy University
 
Python Interpreter.pdf
Python Interpreter.pdfPython Interpreter.pdf
Python Interpreter.pdf
SudhanshiBakre1
 
Getting Started with R
Getting Started with RGetting Started with R
Getting Started with R
Sankhya_Analytics
 
Machine Learning in R
Machine Learning in RMachine Learning in R
Machine Learning in R
Alexandros Karatzoglou
 
Lisp
LispLisp
Lisp
Aniruddha Chakrabarti
 
R Programming
R ProgrammingR Programming
R Programming
Abhishek Pratap Singh
 
Linear Regression With R
Linear Regression With RLinear Regression With R
Linear Regression With R
Edureka!
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
Khaled Al-Shamaa
 
R data-import, data-export
R data-import, data-exportR data-import, data-export
R data-import, data-export
FAO
 
3 Data Structure in R
3 Data Structure in R3 Data Structure in R
3 Data Structure in R
Dr Nisha Arora
 
NumPy/SciPy Statistics
NumPy/SciPy StatisticsNumPy/SciPy Statistics
NumPy/SciPy Statistics
Enthought, Inc.
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function
Sakthi Dasans
 
Python Seaborn Data Visualization
Python Seaborn Data Visualization Python Seaborn Data Visualization
Python Seaborn Data Visualization
Sourabh Sahu
 
NUMPY
NUMPY NUMPY
NUMPY
SharmilaChidaravalli
 
Data manipulation on r
Data manipulation on rData manipulation on r
Data manipulation on r
Abhik Seal
 
R programming slides
R  programming slidesR  programming slides
R programming slides
Pankaj Saini
 
Introduction to R Programming
Introduction to R ProgrammingIntroduction to R Programming
Introduction to R Programming
izahn
 
Descriptive Statistics with R
Descriptive Statistics with RDescriptive Statistics with R
Descriptive Statistics with R
Kazuki Yoshida
 
Introduction to R and R Studio
Introduction to R and R StudioIntroduction to R and R Studio
Introduction to R and R Studio
Rupak Roy
 
Linear Regression With R
Linear Regression With RLinear Regression With R
Linear Regression With R
Edureka!
 
R data-import, data-export
R data-import, data-exportR data-import, data-export
R data-import, data-export
FAO
 
4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function4 R Tutorial DPLYR Apply Function
4 R Tutorial DPLYR Apply Function
Sakthi Dasans
 
Python Seaborn Data Visualization
Python Seaborn Data Visualization Python Seaborn Data Visualization
Python Seaborn Data Visualization
Sourabh Sahu
 

Viewers also liked (20)

Functional Programming in R
Functional Programming in RFunctional Programming in R
Functional Programming in R
David Springate
 
ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5
zukun
 
Securing Windows web servers
Securing Windows web serversSecuring Windows web servers
Securing Windows web servers
Information Technology
 
Scalable Internet Servers and Load Balancing
Scalable Internet Servers and Load BalancingScalable Internet Servers and Load Balancing
Scalable Internet Servers and Load Balancing
Information Technology
 
Functional style programming
Functional style programmingFunctional style programming
Functional style programming
Germán Diago Gómez
 
Trends in spies
Trends in spiesTrends in spies
Trends in spies
Trend Reportz
 
Functional programming with python
Functional programming with pythonFunctional programming with python
Functional programming with python
Marcelo Cure
 
Serial Killers Presentation1
Serial Killers Presentation1Serial Killers Presentation1
Serial Killers Presentation1
Taylor Leszczynski
 
Carrick - Introduction to Physics & Electronics - Spring Review 2012
Carrick - Introduction to Physics & Electronics - Spring Review 2012Carrick - Introduction to Physics & Electronics - Spring Review 2012
Carrick - Introduction to Physics & Electronics - Spring Review 2012
The Air Force Office of Scientific Research
 
CITY OF SPIES BY SORAYYA KHAN
CITY OF SPIES BY SORAYYA KHANCITY OF SPIES BY SORAYYA KHAN
CITY OF SPIES BY SORAYYA KHAN
Sheikh Hasnain
 
Intelligence, spies & espionage
Intelligence, spies & espionageIntelligence, spies & espionage
Intelligence, spies & espionage
dgnadt
 
Lec 03 set
Lec 03   setLec 03   set
Lec 03 set
Naosher Md. Zakariyar
 
What is Network Security?
What is Network Security?What is Network Security?
What is Network Security?
Faith Zeller
 
SAN
SANSAN
SAN
Information Technology
 
Android Application: Introduction
Android Application: IntroductionAndroid Application: Introduction
Android Application: Introduction
Jollen Chen
 
SAN Review
SAN ReviewSAN Review
SAN Review
Information Technology
 
Intoduction to Network Security NS1
Intoduction to Network Security NS1Intoduction to Network Security NS1
Intoduction to Network Security NS1
koolkampus
 
Noah Z - Spies
Noah Z - SpiesNoah Z - Spies
Noah Z - Spies
Mrs. Haglin
 
Xml Publisher
Xml PublisherXml Publisher
Xml Publisher
Duncan Davies
 
Functional Programming in R
Functional Programming in RFunctional Programming in R
Functional Programming in R
David Springate
 
ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5
zukun
 
Scalable Internet Servers and Load Balancing
Scalable Internet Servers and Load BalancingScalable Internet Servers and Load Balancing
Scalable Internet Servers and Load Balancing
Information Technology
 
Functional programming with python
Functional programming with pythonFunctional programming with python
Functional programming with python
Marcelo Cure
 
CITY OF SPIES BY SORAYYA KHAN
CITY OF SPIES BY SORAYYA KHANCITY OF SPIES BY SORAYYA KHAN
CITY OF SPIES BY SORAYYA KHAN
Sheikh Hasnain
 
Intelligence, spies & espionage
Intelligence, spies & espionageIntelligence, spies & espionage
Intelligence, spies & espionage
dgnadt
 
What is Network Security?
What is Network Security?What is Network Security?
What is Network Security?
Faith Zeller
 
Android Application: Introduction
Android Application: IntroductionAndroid Application: Introduction
Android Application: Introduction
Jollen Chen
 
Intoduction to Network Security NS1
Intoduction to Network Security NS1Intoduction to Network Security NS1
Intoduction to Network Security NS1
koolkampus
 
Ad

Similar to Functional Programming in R (20)

An Introduction to Functional Programming at the Jozi Java User Group
An Introduction to Functional Programming at the Jozi Java User GroupAn Introduction to Functional Programming at the Jozi Java User Group
An Introduction to Functional Programming at the Jozi Java User Group
Andreas Pauley
 
An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311
Andreas Pauley
 
OOPS Object oriented Programming PPT Tutorial
OOPS Object oriented Programming PPT TutorialOOPS Object oriented Programming PPT Tutorial
OOPS Object oriented Programming PPT Tutorial
amitnitpatna
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
Recursion in Java
Recursion in JavaRecursion in Java
Recursion in Java
Fulvio Corno
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
Megha V
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
Praveen M Jigajinni
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
manikanta361
 
Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Brief introduction to R Lecturenotes1_R .ppt
Brief introduction to R  Lecturenotes1_R .pptBrief introduction to R  Lecturenotes1_R .ppt
Brief introduction to R Lecturenotes1_R .ppt
geethar79
 
R_Language_study_forstudents_R_Material.ppt
R_Language_study_forstudents_R_Material.pptR_Language_study_forstudents_R_Material.ppt
R_Language_study_forstudents_R_Material.ppt
Suresh Babu
 
Lecture1_R Programming Introduction1.ppt
Lecture1_R Programming Introduction1.pptLecture1_R Programming Introduction1.ppt
Lecture1_R Programming Introduction1.ppt
premak23
 
The Ring programming language version 1.10 book - Part 41 of 212
The Ring programming language version 1.10 book - Part 41 of 212The Ring programming language version 1.10 book - Part 41 of 212
The Ring programming language version 1.10 book - Part 41 of 212
Mahmoud Samir Fayed
 
Dev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingDev Concepts: Functional Programming
Dev Concepts: Functional Programming
Svetlin Nakov
 
sonam Kumari python.ppt
sonam Kumari python.pptsonam Kumari python.ppt
sonam Kumari python.ppt
ssuserd64918
 
Divide and conquer algorithm
Divide and conquer algorithmDivide and conquer algorithm
Divide and conquer algorithm
CHANDAN KUMAR
 
JNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptxJNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
Function in cpu 2
Function in cpu 2Function in cpu 2
Function in cpu 2
Dhaval Jalalpara
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptx
Lizhen Shi
 
An Introduction to Functional Programming at the Jozi Java User Group
An Introduction to Functional Programming at the Jozi Java User GroupAn Introduction to Functional Programming at the Jozi Java User Group
An Introduction to Functional Programming at the Jozi Java User Group
Andreas Pauley
 
An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311
Andreas Pauley
 
OOPS Object oriented Programming PPT Tutorial
OOPS Object oriented Programming PPT TutorialOOPS Object oriented Programming PPT Tutorial
OOPS Object oriented Programming PPT Tutorial
amitnitpatna
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
Megha V
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
manikanta361
 
Brief introduction to R Lecturenotes1_R .ppt
Brief introduction to R  Lecturenotes1_R .pptBrief introduction to R  Lecturenotes1_R .ppt
Brief introduction to R Lecturenotes1_R .ppt
geethar79
 
R_Language_study_forstudents_R_Material.ppt
R_Language_study_forstudents_R_Material.pptR_Language_study_forstudents_R_Material.ppt
R_Language_study_forstudents_R_Material.ppt
Suresh Babu
 
Lecture1_R Programming Introduction1.ppt
Lecture1_R Programming Introduction1.pptLecture1_R Programming Introduction1.ppt
Lecture1_R Programming Introduction1.ppt
premak23
 
The Ring programming language version 1.10 book - Part 41 of 212
The Ring programming language version 1.10 book - Part 41 of 212The Ring programming language version 1.10 book - Part 41 of 212
The Ring programming language version 1.10 book - Part 41 of 212
Mahmoud Samir Fayed
 
Dev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingDev Concepts: Functional Programming
Dev Concepts: Functional Programming
Svetlin Nakov
 
sonam Kumari python.ppt
sonam Kumari python.pptsonam Kumari python.ppt
sonam Kumari python.ppt
ssuserd64918
 
Divide and conquer algorithm
Divide and conquer algorithmDivide and conquer algorithm
Divide and conquer algorithm
CHANDAN KUMAR
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptx
Lizhen Shi
 
Ad

Recently uploaded (20)

Minions Want to eat presentacion muy linda
Minions Want to eat presentacion muy lindaMinions Want to eat presentacion muy linda
Minions Want to eat presentacion muy linda
CarlaAndradesSoler1
 
03 Daniel 2-notes.ppt seminario escatologia
03 Daniel 2-notes.ppt seminario escatologia03 Daniel 2-notes.ppt seminario escatologia
03 Daniel 2-notes.ppt seminario escatologia
Alexander Romero Arosquipa
 
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.pptJust-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
ssuser5f8f49
 
Template_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Template_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnTemplate_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Template_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
cegiver630
 
chapter 4 Variability statistical research .pptx
chapter 4 Variability statistical research .pptxchapter 4 Variability statistical research .pptx
chapter 4 Variability statistical research .pptx
justinebandajbn
 
LLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bertLLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bert
ChadapornK
 
Ch3MCT24.pptx measure of central tendency
Ch3MCT24.pptx measure of central tendencyCh3MCT24.pptx measure of central tendency
Ch3MCT24.pptx measure of central tendency
ayeleasefa2
 
FPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptxFPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptx
ssuser4ef83d
 
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
gmuir1066
 
Secure_File_Storage_Hybrid_Cryptography.pptx..
Secure_File_Storage_Hybrid_Cryptography.pptx..Secure_File_Storage_Hybrid_Cryptography.pptx..
Secure_File_Storage_Hybrid_Cryptography.pptx..
yuvarajreddy2002
 
Data Analytics Overview and its applications
Data Analytics Overview and its applicationsData Analytics Overview and its applications
Data Analytics Overview and its applications
JanmejayaMishra7
 
C++_OOPs_DSA1_Presentation_Template.pptx
C++_OOPs_DSA1_Presentation_Template.pptxC++_OOPs_DSA1_Presentation_Template.pptx
C++_OOPs_DSA1_Presentation_Template.pptx
aquibnoor22079
 
Deloitte Analytics - Applying Process Mining in an audit context
Deloitte Analytics - Applying Process Mining in an audit contextDeloitte Analytics - Applying Process Mining in an audit context
Deloitte Analytics - Applying Process Mining in an audit context
Process mining Evangelist
 
Flip flop presenation-Presented By Mubahir khan.pptx
Flip flop presenation-Presented By Mubahir khan.pptxFlip flop presenation-Presented By Mubahir khan.pptx
Flip flop presenation-Presented By Mubahir khan.pptx
mubashirkhan45461
 
IAS-slides2-ia-aaaaaaaaaaain-business.pdf
IAS-slides2-ia-aaaaaaaaaaain-business.pdfIAS-slides2-ia-aaaaaaaaaaain-business.pdf
IAS-slides2-ia-aaaaaaaaaaain-business.pdf
mcgardenlevi9
 
CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...
CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...
CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...
ThanushsaranS
 
Simple_AI_Explanation_English somplr.pptx
Simple_AI_Explanation_English somplr.pptxSimple_AI_Explanation_English somplr.pptx
Simple_AI_Explanation_English somplr.pptx
ssuser2aa19f
 
1. Briefing Session_SEED with Hon. Governor Assam - 27.10.pdf
1. Briefing Session_SEED with Hon. Governor Assam - 27.10.pdf1. Briefing Session_SEED with Hon. Governor Assam - 27.10.pdf
1. Briefing Session_SEED with Hon. Governor Assam - 27.10.pdf
Simran112433
 
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Abodahab
 
Digilocker under workingProcess Flow.pptx
Digilocker  under workingProcess Flow.pptxDigilocker  under workingProcess Flow.pptx
Digilocker under workingProcess Flow.pptx
satnamsadguru491
 
Minions Want to eat presentacion muy linda
Minions Want to eat presentacion muy lindaMinions Want to eat presentacion muy linda
Minions Want to eat presentacion muy linda
CarlaAndradesSoler1
 
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.pptJust-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
ssuser5f8f49
 
Template_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Template_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnTemplate_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Template_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
cegiver630
 
chapter 4 Variability statistical research .pptx
chapter 4 Variability statistical research .pptxchapter 4 Variability statistical research .pptx
chapter 4 Variability statistical research .pptx
justinebandajbn
 
LLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bertLLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bert
ChadapornK
 
Ch3MCT24.pptx measure of central tendency
Ch3MCT24.pptx measure of central tendencyCh3MCT24.pptx measure of central tendency
Ch3MCT24.pptx measure of central tendency
ayeleasefa2
 
FPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptxFPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptx
ssuser4ef83d
 
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
gmuir1066
 
Secure_File_Storage_Hybrid_Cryptography.pptx..
Secure_File_Storage_Hybrid_Cryptography.pptx..Secure_File_Storage_Hybrid_Cryptography.pptx..
Secure_File_Storage_Hybrid_Cryptography.pptx..
yuvarajreddy2002
 
Data Analytics Overview and its applications
Data Analytics Overview and its applicationsData Analytics Overview and its applications
Data Analytics Overview and its applications
JanmejayaMishra7
 
C++_OOPs_DSA1_Presentation_Template.pptx
C++_OOPs_DSA1_Presentation_Template.pptxC++_OOPs_DSA1_Presentation_Template.pptx
C++_OOPs_DSA1_Presentation_Template.pptx
aquibnoor22079
 
Deloitte Analytics - Applying Process Mining in an audit context
Deloitte Analytics - Applying Process Mining in an audit contextDeloitte Analytics - Applying Process Mining in an audit context
Deloitte Analytics - Applying Process Mining in an audit context
Process mining Evangelist
 
Flip flop presenation-Presented By Mubahir khan.pptx
Flip flop presenation-Presented By Mubahir khan.pptxFlip flop presenation-Presented By Mubahir khan.pptx
Flip flop presenation-Presented By Mubahir khan.pptx
mubashirkhan45461
 
IAS-slides2-ia-aaaaaaaaaaain-business.pdf
IAS-slides2-ia-aaaaaaaaaaain-business.pdfIAS-slides2-ia-aaaaaaaaaaain-business.pdf
IAS-slides2-ia-aaaaaaaaaaain-business.pdf
mcgardenlevi9
 
CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...
CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...
CTS EXCEPTIONSPrediction of Aluminium wire rod physical properties through AI...
ThanushsaranS
 
Simple_AI_Explanation_English somplr.pptx
Simple_AI_Explanation_English somplr.pptxSimple_AI_Explanation_English somplr.pptx
Simple_AI_Explanation_English somplr.pptx
ssuser2aa19f
 
1. Briefing Session_SEED with Hon. Governor Assam - 27.10.pdf
1. Briefing Session_SEED with Hon. Governor Assam - 27.10.pdf1. Briefing Session_SEED with Hon. Governor Assam - 27.10.pdf
1. Briefing Session_SEED with Hon. Governor Assam - 27.10.pdf
Simran112433
 
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Abodahab
 
Digilocker under workingProcess Flow.pptx
Digilocker  under workingProcess Flow.pptxDigilocker  under workingProcess Flow.pptx
Digilocker under workingProcess Flow.pptx
satnamsadguru491
 

Functional Programming in R

  • 1. Functional Programming in R A Pragmatic Introduction Soumendra Prasad Dhanee Data Scientist .com 18th October, 2014 8th November, 2014 (delivered at R Meetup, Mumbai) Soumendra Prasad Dhanee Functional Programming in R Slide 1/51
  • 2. 1 Introduction Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions 2 More about functions Problem 2 Anonymous Functions Problem 3 3 Applicative Programming Map mapply Filter Negate 4 Closure Soumendra Prasad Dhanee Functional Programming in R Slide 2/51
  • 3. Introduction More about functions Applicative Programming Closure Overview We'll start by reviewing basics We'll see the ideas at action
  • 4. rst (by solving problems) and abstractions later We'll digress a lot Soumendra Prasad Dhanee Functional Programming in R Slide 3/51
  • 5. Next ... 1 Introduction Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions 2 More about functions Problem 2 Anonymous Functions Problem 3 3 Applicative Programming Map mapply Filter Negate 4 Closure Soumendra Prasad Dhanee Functional Programming in R Slide 4/51
  • 6. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Writing a function in R func t ionname < f u n c t i o n ( arg1 , arg2 , . . . ) f 1 e x p r e s s i o n s 2 [ r e t u r n (e x p r e s s i o n ) ] 3 g 4 return() is optional last statement of the function body is returned by default Soumendra Prasad Dhanee Functional Programming in R Slide 5/51
  • 7. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Example of a Function s q u a r e . o f f u n c t i o n ( x ) f 1 x*x 2 g 3 Call the function s q u a r e . o f ( 4 ) 1 y s q u a r e . o f ( x=4) 2 s q u a r e . o f ( z=4) 3 Soumendra Prasad Dhanee Functional Programming in R Slide 6/51
  • 8. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions More on Functions Arguments of R functions can be either required or optional, indicated by syntax Required arguments have no default value Optional arguments are de
  • 9. ned to have a default value Soumendra Prasad Dhanee Functional Programming in R Slide 7/51
  • 10. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions More on Functions - Example add f u n c t i o n ( x , y = 2) f 1 x+y 2 g 3 add ( 3 ) 1 add ( 3 , 2 ) 2 add ( x=3) 3 add ( x=3, y=2) 4 add ( y=2) 5 add ( , 3) 6 Soumendra Prasad Dhanee Functional Programming in R Slide 8/51
  • 11. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Example - Computing Power I Write a function that computes the kth power of an argument x, using one default argument, and one optional argument, i.e. an argument that has a default value. We'll be coming back to this function later on. Soumendra Prasad Dhanee Functional Programming in R Slide 9/51
  • 12. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Example - Computing Power II power f u n c t i o n ( x , k=2) x^k 1 Soumendra Prasad Dhanee Functional Programming in R Slide 10/51
  • 13. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions The apply family of functions lapply(X, FUN, ...) returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X sapply(X, FUN, ...) a user-friendly version of lapply by default returning a vector or matrix if appropriate Read the Documentation Soumendra Prasad Dhanee Functional Programming in R Slide 11/51
  • 14. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Vectorized Functions ... functions that operate on vectors or matrices or dataframes. Often much faster than looping over a vector, often use .Internal or .Primitive Higher abstraction - less code to write, less to debug Soumendra Prasad Dhanee Functional Programming in R Slide 12/51
  • 15. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions .Internal and .Primitive - I log ## function (x, base = exp(1)) .Primitive(log) paste ## function (..., sep = , collapse = NULL) ## .Internal(paste(list(...), sep, collapse)) ## bytecode: 0x1f8a2c8 ## environment: namespace:base Soumendra Prasad Dhanee Functional Programming in R Slide 13/51
  • 16. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions .Internal and .Primitive - II colMeans ## function (x, na.rm = FALSE, dims = 1L) ## { ## if (is.data.frame(x)) ## x - as.matrix(x) ## if (!is.array(x) || length(dn - dim(x)) 2L) ## stop( x must be an array of at least two dimensions) ## if (dims 1L || dims length(dn) - 1L) ## stop(invalid dims ) ## n - prod(dn[1L:dims]) ## dn - dn[-(1L:dims)] ## z - if (is.complex(x)) ## .Internal(colMeans(Re(x), n, prod(dn), na.rm)) + Soumendra Prasad Dhanee Functional Programming in R Slide 14/51 ## .Internal(colMeans(Im(x), n, prod(dn), na.rm))
  • 17. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Examples of Vectorized Functions ifelse() is.na() log() sqrt() rnorm() colMeans() rowSums() x y x == y !x Soumendra Prasad Dhanee Functional Programming in R Slide 15/51
  • 18. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Primality Testing I Given a number, decide if it is a prime or not. Hint 1 : min(x) gives the lowest element of vector x min(c(2, 1, 3)) ## [1] 1 Soumendra Prasad Dhanee Functional Programming in R Slide 16/51
  • 19. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Primality Testing II min ( x%%( 2 : ( x1) ) )0 1 The Deconstruction 2 : ( x1) 1 x%%( 2 : ( x1) ) 2 min ( x%%( 2 : ( x1) ) )0 3 Soumendra Prasad Dhanee Functional Programming in R Slide 17/51
  • 20. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Lists of functions x - 1:10 funs - list( sum = sum, mean = mean, median = median ) sapply(funs, function(f) f(x)) ## sum mean median ## 55.0 5.5 5.5 Soumendra Prasad Dhanee Functional Programming in R Slide 18/51
  • 21. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Let's get started Problem 1 Input A numeric vector (1:200000) Output A vector containing the even numbers in the input vector, listed in the order they appeared in the input vector Soumendra Prasad Dhanee Functional Programming in R Slide 19/51
  • 22. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Solution - for loop I Solution using for loop x 1:200000 1 ans l o g i c a l (200000) 2 f o r ( i i n x ) 3 f 4 i f ( i%%2==0) f ans [ i ] = TRUE g e l s e f 5 ans [ i ] = FALSE g 6 g 7 x [ ans ] 8 ## user system elapsed ## 0.542 0.005 0.546 Soumendra Prasad Dhanee Functional Programming in R Slide 20/51
  • 23. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Solution - for loop II Solution using for loop x 1:200000 1 ans c ( ) 2 f o r ( i i n x ) 3 f 4 i f ( i%%2==0) f ans [ i ] = TRUE g e l s e f 5 ans [ i ] = FALSE g 6 g 7 x [ ans ] 8 ## user system elapsed ## 56.511 2.631 59.333 Soumendra Prasad Dhanee Functional Programming in R Slide 21/51
  • 24. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Solution - vectorized functions Solution using vectorized functions x 1:200000 1 ans x%%2==0 2 x [ ans ] 3 ## user system elapsed ## 0.013 0.000 0.013 Soumendra Prasad Dhanee Functional Programming in R Slide 22/51
  • 25. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions Solution - higher-order functions Solution using higher-order functions x 1:200000 1 ans s a p p l y ( x , f u n c t i o n ( i ) i%%2==0) 2 x [ ans ] 3 ## user system elapsed ## 0.554 0.011 0.566 Soumendra Prasad Dhanee Functional Programming in R Slide 23/51
  • 26. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions What are higher-order functions? Higher-order Functions A higher-order function (also functional form, functional or functor) is a function that does at least one of the following: takes one or more functions as an input outputs a function -source - Wikipedia Soumendra Prasad Dhanee Functional Programming in R Slide 24/51
  • 27. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions An example sapply sapply(X, FUN, ...) Soumendra Prasad Dhanee Functional Programming in R Slide 25/51
  • 28. Introduction More about functions Applicative Programming Closure Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions What are
  • 29. rst-class functions? First-class Functions First-class functions are functions that can be treated like any other piece of data ... can be stored in a variable can be stored in a list can be stored in an object can be passed to other functions can be returned from other functions ... just like any other piece of data. Soumendra Prasad Dhanee Functional Programming in R Slide 26/51
  • 30. Next ... 1 Introduction Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions 2 More about functions Problem 2 Anonymous Functions Problem 3 3 Applicative Programming Map mapply Filter Negate 4 Closure Soumendra Prasad Dhanee Functional Programming in R Slide 27/51
  • 31. Introduction More about functions Applicative Programming Closure Problem 2 Anonymous Functions Problem 3 Rounding o Problem 2a Input A numeric vector (rnorm(100, 0, 1)) Output A vector containing all the numbers in the input vector rounded to the nearest integer Soumendra Prasad Dhanee Functional Programming in R Slide 28/51
  • 32. Introduction More about functions Applicative Programming Closure Problem 2 Anonymous Functions Problem 3 Solution 2a - Rounding o Solution using sapply s a p p l y ( rnorm (100 , 0 , 1) , round ) 1 Soumendra Prasad Dhanee Functional Programming in R Slide 29/51
  • 33. Introduction More about functions Applicative Programming Closure Problem 2 Anonymous Functions Problem 3 Rounding o Problem 2b Input A numeric vector (rnorm(100, 0, 1)) Output A vector containing all the numbers in the input vector rounded to two decimal places Soumendra Prasad Dhanee Functional Programming in R Slide 30/51
  • 34. Introduction More about functions Applicative Programming Closure Problem 2 Anonymous Functions Problem 3 Solution 2b - Rounding o Solution using sapply s a p p l y ( rnorm (100 , 0 , 1) , f u n c t i o n ( x ) round ( x , 2) ) 1 Soumendra Prasad Dhanee Functional Programming in R Slide 31/51
  • 35. Introduction More about functions Applicative Programming Closure Problem 2 Anonymous Functions Problem 3 Anonymous Functions Anonymous Functions Anonymous function is a function that is not bound to an identi
  • 36. er. source - Wikipedia Soumendra Prasad Dhanee Functional Programming in R Slide 32/51
  • 37. Introduction More about functions Applicative Programming Closure Problem 2 Anonymous Functions Problem 3 Acting on Matrices Problem 3 Input A 3-by-3 matrix (matrix(1:9, ncol=3)) Output Add 1 to row 1, 4 to row 2, 7 to row 3 Soumendra Prasad Dhanee Functional Programming in R Slide 33/51
  • 38. Introduction More about functions Applicative Programming Closure Problem 2 Anonymous Functions Problem 3 Solution 3 - Matrix Addition Solution using sweep m ma t r i x ( 1 : 9 , n c o l=3) 1 sweep (m, 1 , c ( 1 , 4 , 7) , + ) 2 ## [,1] [,2] [,3] ## [1,] 2 5 8 ## [2,] 6 9 12 ## [3,] 10 13 16 Soumendra Prasad Dhanee Functional Programming in R Slide 34/51
  • 39. Next ... 1 Introduction Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions 2 More about functions Problem 2 Anonymous Functions Problem 3 3 Applicative Programming Map mapply Filter Negate 4 Closure Soumendra Prasad Dhanee Functional Programming in R Slide 35/51
  • 40. Introduction More about functions Applicative Programming Closure Map mapply Filter Negate Applicative Programming Calling by function B of function A, where function A was originally supplied to function B as an argument. Examples map reduce (fold)
  • 41. lter Soumendra Prasad Dhanee Functional Programming in R Slide 36/51
  • 42. Introduction More about functions Applicative Programming Closure Map mapply Filter Negate Map Map(f, x, ...) 1 f u n c t i o n ( f , . . . ) 2 f 3 f match . fun ( f ) 4 mapply (FUN = f , . . . , SIMPLIFY = FALSE) 5 g 6 by t e code : 0 x402ad90 7 env i ronment : namespace : base 8 Soumendra Prasad Dhanee Functional Programming in R Slide 37/51
  • 43. Introduction More about functions Applicative Programming Closure Map mapply Filter Negate mapply mapply is a multivariate version of sapply. mapply ( rep , 1 : 4 , 4 : 1 ) 1 2 mapply ( rep , t ime s = 1 : 4 , x = 4 : 1 ) 3 4 mapply ( rep , x = 1 : 4 , t ime s = 4 : 1 ) 5 Soumendra Prasad Dhanee Functional Programming in R Slide 38/51
  • 44. Introduction More about functions Applicative Programming Closure Map mapply Filter Negate Filter I Choose all the even numbers. F i l t e r ( f u n c t i o n ( x ) x%%2 , 1:200000) 1 ## user system elapsed ## 0.419 0.004 0.424 Soumendra Prasad Dhanee Functional Programming in R Slide 39/51
  • 45. Introduction More about functions Applicative Programming Closure Map mapply Filter Negate Filter II The previous solution was wrong. Now what is the output of the following - F i l t e r ( c (T, F) , 1:200000) 1 Soumendra Prasad Dhanee Functional Programming in R Slide 40/51
  • 46. Introduction More about functions Applicative Programming Closure Map mapply Filter Negate Filter III f u n c t i o n ( f , x ) 1 f 2 i n d as . l o g i c a l ( u n l i s t ( l a p p l y ( x , f ) ) ) 3 x [ ! i s . na ( i n d ) i n d ] 4 g 5 by t e code : 0 x4f87f00 6 env i ronment : namespace : base 7 Soumendra Prasad Dhanee Functional Programming in R Slide 41/51
  • 47. Introduction More about functions Applicative Programming Closure Map mapply Filter Negate Negate I What is the outcome? Negate ( c (T, F) , 1 : 1 0 ) 1 Soumendra Prasad Dhanee Functional Programming in R Slide 42/51
  • 48. Introduction More about functions Applicative Programming Closure Map mapply Filter Negate Negate II What is the outcome? F i l t e r ( Negate ( f u n c t i o n ( x ) x%%2) , 1 : 1 0 ) 1 Soumendra Prasad Dhanee Functional Programming in R Slide 43/51
  • 49. Introduction More about functions Applicative Programming Closure Map mapply Filter Negate Negate III f u n c t i o n ( f ) 1 f 2 f match . fun ( f ) 3 f u n c t i o n ( . . . ) ! f ( . . . ) 4 g 5 by t e code : 0 x4e9c250 6 env i ronment : namespace : base 7 Soumendra Prasad Dhanee Functional Programming in R Slide 44/51
  • 50. Next ... 1 Introduction Getting Started Vectorization Vectorization in Practice Problem 1 Higher-order Functions First-class Functions 2 More about functions Problem 2 Anonymous Functions Problem 3 3 Applicative Programming Map mapply Filter Negate 4 Closure Soumendra Prasad Dhanee Functional Programming in R Slide 45/51
  • 51. Introduction More about functions Applicative Programming Closure Computing Power Revisited Write a function that computes the kth power of an argument x, using one default argument, and one optional argument, i.e. an argument that has a default value. power f u n c t i o n ( x , k=2) f 1 x^k 2 g 3 Soumendra Prasad Dhanee Functional Programming in R Slide 46/51
  • 52. Introduction More about functions Applicative Programming Closure Function Factory with Closures A function returning a function: power f u n c t i o n ( e xponent ) f 1 f u n c t i o n ( x ) f 2 x ^ e xponent 3 g 4 g 5 6 s q u a r e power ( 2 ) 7 s q u a r e ( 2 ) 8 s q u a r e ( 4 ) 9 10 cube power ( 3 ) 11 cube ( 2 ) 12 cube ( 4 ) 13 Soumendra Prasad Dhanee Functional Programming in R Slide 47/51
  • 53. Introduction More about functions Applicative Programming Closure What are Closures? An object is data with functions. A closure is a function with data. - John D. Cook ... an abstraction binding a function to its scope. - Wikipedia Closures get their name because they enclose the environment of the parent function and can access all its variables. - Hadley Wickham Soumendra Prasad Dhanee Functional Programming in R Slide 48/51
  • 54. Introduction More about functions Applicative Programming Closure Closer look at closures I square ## function(x) { ## x ^ exponent ## } ## environment: 0x217dcf8 cube ## function(x) { ## x ^ exponent ## } ## environment: 0x26cb1d0 Soumendra Prasad Dhanee Functional Programming in R Slide 49/51
  • 55. Introduction More about functions Applicative Programming Closure Closer look at closures II as.list(environment(square)) ## $exponent ## [1] 2 as.list(environment(cube)) ## $exponent ## [1] 3 Soumendra Prasad Dhanee Functional Programming in R Slide 50/51
  • 56. Introduction More about functions Applicative Programming Closure Closer look at closures III l i b r a r y ( p r y r ) 1 u n e n c l o s e ( s q u a r e ) 2 # f u n c t i o n ( x ) 3 # f 4 # x ^2 5 # g 6 u n e n c l o s e ( cube ) 7 # f u n c t i o n ( x ) 8 # f 9 # x ^3 10 # g 11 Soumendra Prasad Dhanee Functional Programming in R Slide 51/51