# 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:

1 2 3 4 5 6 7 8 |
function_name = function(argument 1, argument 2, …) { function body return(value or return object) } |

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

1 2 3 4 5 6 7 8 9 |
our_function = function(vector, number) { out = vector * number out = sum(out) return(out) } |

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

1 2 3 4 5 6 7 |
v = c(1:5) n = 4 out <- out_function(v,n) print(out) |

Result is:

1 2 |
print(out) [1] 60 |

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

1 2 |
out = our_function(v) Error in funkcja(v) : argument "number" is missing, with no default |

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:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
our_function = function(vector, number = NULL) { if(is.null(number) { out = sum(number) } else { out = vector * number out = sum(out) } return(out) } |

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

1 2 3 |
v = c(1:5) out = our_function(v) print(out) |

Result is:

1 2 |
print(wynik) [1] 15 |

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.