02 Functions in R
02 Functions in R
02 Functions in R
Writing Functions
Ken Rice
Thomas Lumley
• Structure of a function
9.1
Introduction
Functions are an important part of R because they allow the user
to customize and extend the language.
9.2
Structure of a function
Functions are created using the function() directive and are
stored as R objects.
9.3
Structure of a function
The basic structure of a function is:
9.4
Calling a function
Functions are called by their name followed by parentheses
containing possible argument names.
or
• Variables that are created inside the function body exist only
for the lifetime of the function. This means they are not
accessible outside of the function, in an R session
9.6
Example: returning a single value
Here’s a function for calculating the coefficient of variation (the
ratio of the standard deviation to the mean) for a vector;
9.8
Example: returning multiple values
Applying our popn.mean.sd() function to the daily ozone concen-
trations in New York data;
9.9
Declaring functions within functions
Usually, functions that take arguments, execute R commands,
and return output will be enough. But functions can be declared
and used inside a function;
> square.plus.cube(4)
[1] 80
9.10
Example: function returning a function
And functions can also return other functions, as output;
9.12
Example: functions as arguments
A function to implement the Newton-Raphson method, given
input of arguments, a place to start, and convergence tolerance:
p p
b2 32 + 4 × 5
myf(x)
−b ± − 4ac −3 ±
60
=
2a 2
40
≈ −4.19, 1.19
20
9.14
Tips for writing functions
• Avoid rewriting the same code... use functions!
9.15
Summary (so far)
• User-defined functions are easy to create in R, with my.fun <-
function(argument list)
9.16
Shiny: a quick look
It’s also possible to display data analyses on websites – and have
them be interactive. The shiny package, by RStudio, builds
‘apps’ that do this - using function definitions, in scripts.
9.18
Shiny: server.R
library("shiny")
# first, a local copy of salary data sits in same directory
salary <- read.table("salaryShinyCopy.txt", header=T)
9.19
Shiny: making it work in Rstudio
This is remarkably straightforward;
9.23