8 Functions
8.0.1 Function Overview
Functions are objects and are assigned to names, just like data.
myFunction = function(argument1,argument2) { expression1 expression2 }
We write functions for anything we need to do again and again.
You may test your commands interactively at first, and then use the
history()
feature and an editor to create the function.It is wise to include a comment at the start of each function to say what it does and to document functions of more than a few lines.
8.0.2 Example Functions
add1 = function(x) {
# this function adds one to the first argument and returns it
x + 1
}
add1(17)
## [1] 18
add1(c(17,18,19,20))
## [1] 18 19 20 21
You can use the edit()
function to make changes to a function. The following command will open a window, allow you to make changes, and assign the result to a new function, add2
.
add2 = edit(add1)
8.0.3 Further Reading
The amount of learning material for R is simply astonishing!