3.6 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.5) or an operator (Section 3.7).
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.
## [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.19.
We can define out own functions:
A shorthand for function() introduced in 2021 is:
This syntax is most useful for anonymous functions inline.
Your donation will support ongoing availability and give you access to the PDF version of this 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-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0
