Source: https://www.stats.ox.ac.uk/~evans/Rprog/LectureNotes.pdf