Writing functions in R

Special three dots parameter

This parameter is typically used for pass parameters on to functions called within a function. function(x,...)

For example:

The ... parameter allows a function to take any named parameter at all. If you write a function without it, it will only take the specified parameters, but if you add this parameter, it will accept any named parameter at all:

Functions without names

## [1] 9

Lazy evaluation

Expressions used in a function call are not evaluated before they are passed to the function. Most common languages have so-called pass by-value semantics, which means that all expressions given to parameters of a function are evaluated before the function is called. In R, the semantic is call-by-promise, also known as lazy evaluation.

Vectorized function

Expressions in R are vectorized. When you write an expression, it is implicitly working on vectors of values, not single values. Even simple expressions that only involve numbers really are vector operations. They are just vectors of length 1.

If the function is already vectorized and we use Vectorize() function, we break the function.

Infix operators

## [1] 0.4
## [1] 10
## [1] 7
## [1] -3
## [1] 32
## [1] FALSE
## [1] "FALSE"

Replacement functions