[1] 5
Functions are a relatively complex and advanced topic. We will cover them later. Since we use them right from the start (e.g. the mean function to compute the mean), it is important to be clear about a few aspects:
We can think of functions in R in the same way as classic mathematical functions. Given some input values, functions perform specific calculations and return the result as output.
We have already seen that everything in R is an object. Functions too, although very different from other elements, are created and treated in R as objects. In this example, we create a function that takes x as input and adds the value 3 to x.
The output will depend on the value of x.
[1] 10
We can create, remove or overwrite them like any other object. We will see later how to create them, but keep in mind that all the functions we use are created as objects and stored in the environment.
Function arguments are what we, as users, need to know and set correctly so that the function does what it was designed to do. In the previous example the only argument was x. Let’s look at the help of the mean() function instead.
There are 2 rules for setting these arguments:
x = vector, na.rm = TRUE, etc.argument = value, but I must respect the order in which the function was written.Let’s try to use the mean() function:
[1] 1.012073
In R we can install and load additional packages, which simply make available libraries of functions created by other users. To use a package:
Install the package with install.packages("packagename")
Load the package with library(packagename)
Access a function without loading the package with packagename::functionname() (useful if you only need one function or if there are conflicts)
In R, errors are:
There are different alert levels when we write code:
messages: the function returns something that is useful to know, but everything is fine
warnings: the function informs us about something potentially problematic, but (more or less) everything is fine
errors: the function not only informs us about an error, but the requested operations were not executed
Every function has a documentation page, accessible with ?functionname, ??functionname or help(functionname)
We can also look up the package documentation
We can search online for the function name or for the message we get
Stack overflow is a discussion forum about anything involving code (statistics, programming, etc.). It is full of common errors, How to do … questions and extremely useful answers/solutions. In 90% of cases the problem you have is common and a solution already exists.
Be careful
Ask the question clearly
Make sure you have understood the answer
Double-check!