<- function(x, y) {
compare == y
x }
Function definition
R comes with a number of built-in functions. Packages can provide additional ones. In many cases however, you will want to create your own functions to perform exactly the computations that you need.
In this section, we will see how to define new functions.
Syntax
Here is the syntax to define a new function:
name <- function(arguments) {
body }
Example
Let’s define a function that we call compare
which will compare the value between 2 numbers:
compare
is the name of our function.x
andy
are the placeholders for the arguments that our function will accept (our function will need 2 arguments to run successfully).x == y
is the body of the function, that is, the computation performed by our function.
We can now use our function:
compare(2, 3)
[1] FALSE
What is returned by a function?
In R, the result of the last statement is printed automatically:
<- function(x, y) {
test
x
y
}test(2, 3)
[1] 3
If you want to also print other results, you need to explicitly use the print()
function:
<- function(x, y) {
test print(x)
y
}test(2, 3)
[1] 2
[1] 3
Note that, unlike print()
, the function return()
exits the function:
<- function(x, y) {
test return(x)
y
}test(2, 3)
[1] 2
<- function(x, y) {
test return(x)
return(y)
}test(2, 3)
[1] 2