3.5 Functions

20210103 When using R we write commands that instruct the R software to perform particular actions. Formally commands are actually functions which mathematically operate on a set of inputs and produces an output. R provides a wealth of functions and these form the verbs of the language we use to construct sentences. The verbs are the doing words! Although technically everything is a function in R we can generally think of each verb as either a function, a command (Section 3.4) or an operator (Section 3.6).

All functions in R take arguments and return values. When we invoke a function (as distinct from what we will identify as a command) we are interested in the value that it returns. Below is a simple example base::sum()ing two numbers.

# Add two numbers.

sum(1, 2)
## [1] 3

Here the function has returned a single value, though it is technically returned as a vector of length 1 containing just the item 3. The result can be stored into a variable as discussed in Section 3.18.

We can define out own functions:

mysum <- function(x) x + 1

A shorthand for function() introduced in 2021 is:

mysum <- \(x) x + 1

This syntax is most useful for anonymous functions inline.

sapply(1:10, \(x) x + 1)

Your donation will support ongoing development and give you access to the PDF version of the book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984.
Copyright © 1995-2021 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0.