<- function() {
f ## This is an empty function
}## Functions have their own class
class(f)
[1] "function"
## Execute this function
f()
NULL
September 22, 2022
Material for this lecture was borrowed and adopted from
Writing functions is a core activity of an R programmer. It represents the key step of the transition from a mere “user” to a developer who creates new functionality for R.
Functions are often used to encapsulate a sequence of expressions that need to be executed numerous times, perhaps under slightly different conditions.
Also, functions are also often written when code must be shared with others or the public.
The writing of a function allows a developer to create an interface to the code, that is explicitly specified with a set of arguments (or parameters).
This interface provides an abstraction of the code to potential users. This abstraction simplifies the users’ lives because it relieves them from having to know every detail of how the code operates.
In addition, the creation of an interface allows the developer to communicate to the user the aspects of the code that are important or are most relevant.
Functions in R are “first class objects”, which means that they can be treated much like any other R object.
If you are familiar with common language like C, these features might appear a bit strange. However, they are really important in R and can be useful for data analysis.
Functions are defined using the function()
directive and are stored as R objects just like anything else.
Not very interesting, but it is a start!
The next thing we can do is create a function that actually has a non-trivial function body.
Hello, world!
The last aspect of a basic function is the function arguments.
These are the options that you can specify to the user that the user may explicitly set.
For this basic function, we can add an argument that determines how many times “Hello, world!” is printed to the console.
Hello, world!
Hello, world!
Hello, world!
Obviously, we could have just cut-and-pasted the cat("Hello, world!\n")
code three times to achieve the same effect, but then we wouldn’t be programming, would we?
Also, it would be un-neighborly of you to give your code to someone else and force them to cut-and-paste the code however many times the need to see “Hello, world!”.
Finally, the function above doesn’t return anything.
It just prints “Hello, world!” to the console num
number of times and then exits.
But often it is useful if a function returns something that perhaps can be fed into another section of code.
This next function returns the total number of characters printed to the console.
f <- function(num) {
hello <- "Hello, world!\n"
for(i in seq_len(num)) {
cat(hello)
}
chars <- nchar(hello) * num
chars
}
meaningoflife <- f(3)
Hello, world!
Hello, world!
Hello, world!
[1] 42
In the above function, we did not have to indicate anything special in order for the function to return the number of characters.
In R, the return value of a function is always the very last expression that is evaluated.
Because the chars
variable is the last expression that is evaluated in this function, that becomes the return value of the function.
Finally, in the above function, the user must specify the value of the argument num
. If it is not specified by the user, R will throw an error.
We can modify this behavior by setting a default value for the argument num
.
Any function argument can have a default value, if you wish to specify it.
Sometimes, argument values are rarely modified (except in special cases) and it makes sense to set a default value for that argument. This relieves the user from having to specify the value of that argument every single time the function is called.
Here, for example, we could set the default value for num
to be 1, so that if the function is called without the num
argument being explicitly specified, then it will print “Hello, world!” to the console once.
f <- function(num = 1) {
hello <- "Hello, world!\n"
for(i in seq_len(num)) {
cat(hello)
}
chars <- nchar(hello) * num
chars
}
f() ## Use default value for 'num'
Hello, world!
[1] 14
Hello, world!
Hello, world!
[1] 28
Remember that the function still returns the number of characters printed to the console.
We have written a function that
has one formal argument named num
with a default value of 1. The formal arguments are the arguments included in the function definition.
prints the message “Hello, world!” to the console a number of times indicated by the argument num
returns the number of characters printed to the console
Above, we have learned that functions have named arguments, which can optionally have default values.
Because all function arguments have names, they can be specified using their name.
Specifying an argument by its name is sometimes useful if a function has many arguments and it may not always be clear which argument is being specified.
Here, our function only has one argument so there’s no confusion.
Calling an R function with multiple arguments can be done in a variety of ways.
This may be confusing at first, but it’s really handy when doing interactive work at the command line. R functions arguments can be matched positionally or by name.
So, in the following call to rnorm()
100 is assigned to the n
argument, 2 is assigned to the mean
argument, and 1 is assigned to the sd
argument, all by positional matching.
The following calls to the sd()
function (which computes the empirical standard deviation of a vector of numbers) are all equivalent.
When specifying the function arguments by name, it doesn’t matter in what order you specify them.
In the example below, we specify the na.rm
argument first, followed by x
, even though x
is the first argument defined in the function definition.
You can mix positional matching with matching by name.
When an argument is matched by name, it is “taken out” of the argument list and the remaining unnamed arguments are matched in the order that they are listed in the function definition.
Here, the mydata
object is assigned to the x
argument, because it’s the only argument not yet specified.
Below is the argument list for the lm()
function, which fits linear models to a dataset.
function (formula, data, subset, weights, na.action, method = "qr",
model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE,
contrasts = NULL, offset, ...)
NULL
The following two calls are equivalent.
Most of the time, named arguments are helpful:
For example, plotting functions often have a lot of options to allow for customization, but this makes it difficult to remember exactly the position of every argument on the argument list.
Function arguments can also be partially matched, which is useful for interactive work.
Partial matching should be avoided when writing longer code or programs, because it may lead to confusion if someone is reading the code. However, partial matching is very useful when calling functions interactively that have very long argument names.
Arguments to functions are evaluated lazily, so they are evaluated only as needed in the body of the function.
In this example, the function f()
has two arguments: a
and b
.
This function never actually uses the argument b
, so calling f(2)
will not produce an error because the 2 gets positionally matched to a
.
This behavior can be good or bad. It’s common to write a function that doesn’t use an argument and not notice it simply because R never throws an error.
This example also shows lazy evaluation at work, but does eventually result in an error.
[1] 45
Error in print(b): argument "b" is missing, with no default
Notice that “45” got printed first before the error was triggered! This is because b
did not have to be evaluated until after print(a)
.
Once the function tried to evaluate print(b)
the function had to throw an error.
...
ArgumentThere is a special argument in R known as the ...
argument, which indicates a variable number of arguments that are usually passed on to other functions.
The ...
argument is often used when extending another function and you do not want to copy the entire argument list of the original function
For example, a custom plotting function may want to make use of the default plot()
function along with its entire argument list. The function below changes the default for the type
argument to the value type = "l"
(the original default was type = "p"
).
myplot <- function(x, y, type = "l", ...) {
plot(x, y, type = type, ...) ## Pass '...' to 'plot' function
}
Generic functions use ...
so that extra arguments can be passed to methods.
The ...
argument is necessary when the number of arguments passed to the function cannot be known in advance. This is clear in functions like paste()
and cat()
.
[1] "one two three"
[1] "one_two_three_four_five"
Because paste()
prints out text to the console by combining multiple character vectors together, it is impossible for this function to know in advance how many character vectors will be passed to the function by the user.
So the first argument in the function is ...
.
...
ArgumentOne catch with ...
is that any arguments that appear after ...
on the argument list must be named explicitly and cannot be partially matched or matched positionally.
Take a look at the arguments to the paste()
function.
With the paste()
function, the arguments sep
and collapse
must be named explicitly and in full if the default values are not going to be used.
Here, I specify that I want “a” and “b” to be pasted together and separated by a colon.
If I don’t specify the sep
argument in full and attempt to rely on partial matching, I don’t get the expected result.
As you start to write your own functions, it’s important to keep in mind that functions are not just for the computer, but are also for humans. Technically, R does not care what your function is called, or what comments it contains, but these are important for human readers.
This section discusses some things that you should bear in mind when writing functions that humans can understand.
In an ideal world, you want the name of your function to be short but clearly describe what the function does. This is not always easy, but here are some tips.
The function names should be verbs, and arguments should be nouns.
There are some exceptions:
mean()
is better than compute_mean()
).If your function name is composed of multiple words, use “snake_case”, where each lowercase word is separated by an underscore.
“camelCase” is a popular alternative. It does not really matter which one you pick, the important thing is to be consistent: pick one or the other and stick with it.
R itself is not very consistent, but there is nothing you can do about that. Make sure you do not fall into the same trap by making your code as consistent as possible.
If you have a family of functions that do similar things, make sure they have consistent names and arguments.
It’s a good idea to indicate that they are connected. That is better than a common suffix because autocomplete allows you to type the prefix and see all the members of the family.
Where possible, avoid overriding existing functions and variables.
It is impossible to do in general because so many good names are already taken by other packages, but avoiding the most common names from base R will avoid confusion.
Use comments are lines starting with #. They can explain the “why” of your code.
You generally should avoid comments that explain the “what” or the “how”. If you can’t understand what the code does from reading it, you should think about how to rewrite it to be more clear.
However, your code can never capture the reasoning behind your decisions:
It’s a great idea to capture that sort of thinking in a comment.
The last component of a function is its environment.
This is not something you need to understand deeply when you first start writing functions. However, it’s important to know a little bit about environments because they are crucial to how functions work.
The environment of a function controls how R finds the value associated with a name.
For example, take this function:
In many programming languages, this would be an error, because y
is not defined inside the function.
In R, this is valid code because R uses rules called lexical scoping to find the value associated with a name.
Since y
is not defined inside the function, R will look in the environment where the function was defined:
This behavior seems like a recipe for bugs, and indeed you should avoid creating functions like this deliberately, but by and large it does not cause too many problems (especially if you regularly restart R to get to a clean slate).
The advantage of this behavior is that from a language standpoint it allows R to be very consistent.
For f()
that includes the behavior of two things that you might not expect: {
and +
. This allows you to do devious things like:
`+` <- function(x, y) {
if (runif(1) < 0.1) {
sum(x, y)
} else {
sum(x, y) * 1.1
}
}
table(replicate(1000, 1 + 2))
3 3.3
93 907
This is a common phenomenon in R. R places few limits on your power. You can do many things that you can’t do in other programming languages. You can do many things that 99% of the time are extremely ill-advised (like overriding how addition works!). But this power and flexibility is what makes tools like ggplot2
and dplyr
possible.
Functions can be defined using the function()
directive and are assigned to R objects just like any other R object
Functions have can be defined with named arguments; these function arguments can have default values
Functions arguments can be specified by name or by position in the argument list
Functions always return the last expression evaluated in the function body
A variable number of arguments can be specified using the special ...
argument in a function definition.
Here are some post-lecture questions to help you think about the material discussed.