Data science for Engineers
Advanced programming in R: Functions
Advanced Programming in R: Functions (cont.) NPTEL NOC18-CS28 1
Data science for Engineers
In this lecture
Functions
◦ MIMO
Source (load) and call (invoke)
Inline functions
Looping over objects
◦ apply
◦ lapply
◦ tapply
Advanced Programming in R: Functions (cont.) NPTEL NOC18-CS28 2
Data science for Engineers
Multiple input and multiple output functions
Function with multiple inputs and outputs
Functions in R take multiple input objects but returns only one
object as output
This however is not a limitation, because a list object (collection
of several objects) can be returned by function
Diameter Volume
volcylinder_mimo
Height list(volume, surface area)
Surface area
Advanced Programming in R: Functions (cont.) NPTEL NOC18-CS28 3
Data science for Engineers
Creating and saving
1. Creating a function file
2. Save the function file “volcylinder_mimo”
Advanced Programming in R: Functions (cont.) NPTEL NOC18-CS28 4
Data science for Engineers
Loading and invoking
3. Load the function file
4. Execute
Advanced Programming in R: Functions (cont.) NPTEL NOC18-CS28 5
Data science for Engineers
Inline functions
Example of an inline function
func = function(x) x^2+4*x+4
Advanced Programming in R: Functions (cont.) NPTEL NOC18-CS28 6
Data science for Engineers
Looping over objects
There are a few looping functions that are pretty useful
when working interactively on a command line
◦ apply: Apply a function over the margins of an array or matrix
◦ lapply: Apply a function over a list or a vector
◦ tapply: Apply a function over a ragged array
◦ mapply: Multivariate version of lapply
◦ xxply (plyr package)
Advanced Programming in R: Functions (cont.) NPTEL NOC18-CS28 7
Data science for Engineers
apply function
Applies a given function over the margins of a
given array.
◦ Syntax: apply(array, margins, function,…)
◦ Here margins refer to the dimension of the array
along which the function need to be applied.
Advanced Programming in R: Functions (cont.) NPTEL NOC18-CS28 8
Data science for Engineers
lapply function
lapply is used to apply a function over a list.
lapply always returns a list of the same
length as the input list
◦ Syntax: lapply(list, function, …)
Advanced Programming in R: Functions (cont.) NPTEL NOC18-CS28 9
Data science for Engineers
mapply function
• mapply is a multivariate version of lapply.
• A function can be applied over several lists
simultaneously.
◦ Syntax: mapply(fun, list1, list2, …)
Advanced Programming in R: Functions (cont.) NPTEL NOC18-CS28 10
Data science for Engineers
tapply function
tapply is used to apply a function over subset of
vectors given by a combination of factors
◦ Syntax: tapply(vector, factors, function, …)
Advanced Programming in R: Functions (cont.) NPTEL NOC18-CS28 11