Session Ready
Exercise

Defining functions

You will encounter situations in which the function you need does not already exist. R permits you to write your own. Let's practice one such situation, in which you first need to define the function to be used. The functions you define can have multiple arguments as well as default values.

To define functions we use function. For example the following function adds 1 to the number it receives as an argument:

my_func <- function(x){
    y <- x + 1
    y
}

The last value in the function, in this case that stored in y, gets returned.

If you run the code above R does not show anything. This means you defined the function. You can test it out like this:

my_func(5)
Instructions
100 XP

We will define a function sum_n for this exercise.

  • Create a function sum_n that for any given value, say n, creates the vector 1:n, and then computes the sum of the integers from 1 to n.
  • Use the function you just defined to determine the sum of integers from 1 to 5,000.