1 Functions

1.1 Using functions

For help on writing functions, see here.

In R, you use functions to incorporate sets of instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a sub program and called when needed. A function is a piece of code written to carry out a specified task, and can accept zero or more arguments or parameters and it can or can not return one or more values. Additionally, R functions can take additional optional arguments that generally adjust how the function carries out its task.

For example, most mathematical operations beyond arithmetic are supported by specific R functions, such as sqrt for finding the square root. To call a function, we first state its name followed by a matching pair of parentheses (). Our arguments to the function are listed inside the parentheses, so we find \(\sqrt{2}\) as

sqrt(2)
## [1] 1.414214

Some functions don’t require arguments, for example the ls function will list the names of all of the variables you have defined in your current R session:

ls()

Additionally, some functions can take optional arguments which adjust their functionality. Optional arguments aren’t required to evaluate the function, but when supplied they often change the result. Optional arguments are passed with the other functions arguments, but are identified by their name. For example, the log function calculates logarithms and defaults to natural logs:

log(10)
## [1] 2.302585

However, we can change the base of the logarithm by supplying a value to the optional base argument:

log(10,base=10)
## [1] 1
log(10,base=2)
## [1] 3.321928

1.2 Basic maths functions

R support the following standard maths functions, including the following

  • Logarithms: log (base \(e\)), log10 (base 10), log2 (base 2)
  • Exponential: exp(x) (\(e^x\))
  • Trigonometric functions: sin, cos, tan, asin (\(\sin^{-1}\)), acos (\(\cos^{-1}\)), atan (\(\tan^{-1}\))
  • Binomial coefficients: choose(n, x) (\(\binom{n}{x}\))
  • Gamma function: gamma(x) (\(\Gamma(x)\))

All of the basic functions work with scalar and vector arguments. When a basic function is given a vector, it simply evaluates the function for every element.

R Help: Logarithms and Exponentials, Trigonometric Functions, , Binomial coefficient and Gamma

1.3 Writing functions

See Writing your own functions.