Data Science Desktop Survival Guide by Graham Williams Desktop Survival Project Home Preface Data Science Introducing R R Constructs R Tasks R Strings R Read, Write, and Create Data Template Data Exploration Data Wrangling Data Visualisation Statistics ML Template ML Scenarios ML Activities ML Applications ML Algorithms Cluster Analysis Decision Trees Computer Vision Graph Data Privacy Literate Data Science Coding with Style Resources Bibliography Index

## 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.

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)