Lesson 3 of 14 · 11 min
Functions and Packages
A function is a ready-made tool that has a name and does one job for you. You use, or call, a function by writing its name followed by round brackets, and you put the input values it needs, called arguments, inside those brackets. When R finishes, it prints the answer with a [1] label that simply marks the first item in the result.
# c() combines several numbers into one vector (a single ordered list of values)
temps <- c(21, 23, 20, 25, 19)
mean(temps) # the average of the five numbers
sum(temps) # the total of the five numbers[1] 21.6
[1] 108
Some functions accept more than one argument. round() rounds a number to the nearest whole number, and its digits argument lets you instead keep a chosen number of decimal places, for example digits = 1 to keep one decimal. sort() arranges the values of a vector from smallest to largest. Every function also comes with a help page: type ?mean in the console to open the page for mean(), where you can read about extra arguments such as na.rm, which tells mean() to skip missing values written as NA.
round(mean(temps)) # the average (21.6) rounded to the nearest whole number
sort(temps) # the same numbers in ascending order[1] 22
[1] 19 20 21 23 25
You are not limited to the functions that come with R; you can build your own with the function() keyword. You choose a name, list the arguments in the brackets after the word function, and write the job to do between the curly braces. The value on the last line is what your function gives back. The example below turns a temperature in Celsius into Kelvin by adding 273.15.
celsius_to_kelvin <- function(celsius) {
celsius + 273.15
}
celsius_to_kelvin(25) # call your new function with 25 as the argument[1] 298.15
R can be extended with packages, which are bundles of extra functions written by other people. You download a package once with install.packages(), giving the package name in quotation marks. After that, you load it with library() at the start of every new session so its functions become available. Here we install and load seqinr, a package for working with biological sequences.
install.packages("seqinr") # download once; needs an internet connection
library(seqinr) # load it in every new R session before useTry it yourself: Make a vector of five numbers with c(), then find its largest value with max() and its smallest with min(). Next, write a tiny function called double_it that takes one number and returns that number multiplied by 2, and call it on 7 to check you get 14. Finally, open the help page for max() by typing ?max and see which arguments it accepts.