4.7 Functions

Functions are the things that do all the work for us in R: calculate, manipulate data, read and write to files, produce plots. R has many built in functions and we will also be loading more specialized functions from “packages.”

We’ve already seen several functions: c( ), length( ), and plot( ). Let’s now have a look at sum( ).

sum(myvec)
## [1] 135

We called the function sum with the argument myvec, and it returned the value 135. We can get help on how to use sum with:

?sum

Some functions take more than one argument. Let’s look at the function rep, which means “repeat,” and which can take a variety of different arguments. In the simplest case, it takes a value and the number of times to repeat that value.

rep(42, 10)
##  [1] 42 42 42 42 42 42 42 42 42 42

As with many functions in R—which is obsessed with vectors—the thing to be repeated can be a vector with multiple elements.

rep(c(1,2,3), 10)
##  [1] 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3

So far we have used positional arguments, where R determines which argument is which by the order in which they are given. We can also give arguments by name. For example, the above is equivalent to

rep(c(1,2,3), times=10)
##  [1] 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
rep(x=c(1,2,3), 10)
##  [1] 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
rep(times=10, x=c(1,2,3))
##  [1] 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3

Arguments can have default values, and a function may have many different possible arguments that make it do obscure things. For example, rep can also take an argument each=. It’s typical for a function to be invoked with some number of positional arguments, which are always given, plus some less commonly used arguments, typically given by name.

rep(c(1,2,3), each=3)
## [1] 1 1 1 2 2 2 3 3 3
rep(c(1,2,3), each=3, times=5)
##  [1] 1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3 1 1
## [39] 1 2 2 2 3 3 3

4.7.1 Challenge: using functions

Questions
1. Use sum to sum from 1 to 10,000.

  1. Look at the documentation for the seq function. What does seq do? Give an example of using seq with either the by or length.out argument.