R Basics – Functions

From the posts on getting started with R, we already know how to use functions stored in packages developed by other users. Now we will learn how to create our own functions in R. Functions are useful for encapsulating transformations that are often repeated in our code, or for improving readability. The basic syntax of a function in R looks like this:

Let’s write a function that multiplies any vector by the given number and then sums the elements of the vector:

Let’s run our function for the two defined variables:

Result is:

To execute the function, we need to define both arguments. What happens if we don’t add them:

We get an error message that the second argument is missing and we have not defined its default value. So, let’s define the default value of the argument “number” as NULL and write some code in our function which, if this argument has the default value, will return only the sum of the elements of the vector:

Let’s run our new function by passing only the first argument:

Result is:

Functions are very useful when we need to write a long script. They allow us to break the main body of the code into smaller chunks that are easier for the next user of the script or for us to change. In the next part of this course, we will show you how to use R functions in data analysis.

Leave a Reply

Your email address will not be published.

Translate using Google Translate»
Social media & sharing icons powered by UltimatelySocial

Podoba Ci się nasza strona? Odwiedź nasz profil