Section 4 Functions

4.1 Introducing functions

(We’ve been using some functions already, but we’ll now discuss these explicitly). R has lots of functions we can use for doing various things (and you can even create your own). For example, the function mean() will calculate the arithmetic mean of the elements of a vector:

x <- 1:10
mean(x)
## [1] 5.5

4.2 Arguments

Functions typically have various arguments that we can either specify, or leave unspecified, in which case they will take default values.

For example, if we do

y <- c(5, 10, 6, 11, 7, 12)
sort(y)
## [1]  5  6  7 10 11 12

then we can see that sort(y) has sorted the elements of y into increasing order. To sort them into decreasing order, we add an argument decreasing = TRUE:

sort(y, decreasing = TRUE)
## [1] 12 11 10  7  6  5

4.2.1 Experiment!

It’s a good idea to experiment with function arguments, to understand how a function works. For example, try this command

seq(from = 0, to = 10, length = 11)
##  [1]  0  1  2  3  4  5  6  7  8  9 10

then experiment with changing the numbers for the three arguments from, to and length. Try to predict what the effect of any change will be, before running the command.

4.3 Help files

All functions have help files, which tell you a bit more about how the function works, and often provide examples. Use a ? with the function name:

?sort

Help files can be a little overwhelming! If you scroll to the end of a help file, there are usually some examples you can try: trying the examples can often help you to understand how a function works.

Exercise 4.1 Rolling dice.

  1. Suppose a 6-sided dice is rolled once. Try the command
sample(1:6, size = 1)

to get R to simulate the dice roll. Use the up arrow key on your keyboard to bring up the command again, and press return. Do this a few times to check that you get different results each time.

  1. Now suppose the 6-sided dice is rolled six times. Try changing the size argument to 6:
sample(1:6, size = 6)
  1. Run the command above a few times (again, use the up arrow on your keyboard, so you don’t have to keep typing it.) Something about the results you get should look odd. Look at the help file for sample, and see what that default arguments are. What do you need to change, to get more realistic behaviour when simulating 6 dice rolls?