R Language Writing functions in R Named functions


R is full of functions, it is after all a functional programming language, but sometimes the precise function you need isn't provided in the Base resources. You could conceivably install a package containing the function, but maybe your requirements are just so specific that no pre-made function fits the bill? Then you're left with the option of making your own.

A function can be very simple, to the point of being being pretty much pointless. It doesn't even need to take an argument:

one <- function() { 1 }
[1] 1

two <- function() { 1 + 1 }
[1] 2

What's between the curly braces { } is the function proper. As long as you can fit everything on a single line they aren't strictly needed, but can be useful to keep things organized.

A function can be very simple, yet highly specific. This function takes as input a vector (vec in this example) and outputs the same vector with the vector's length (6 in this case) subtracted from each of the vector's elements.

vec <- 4:9
subtract.length <- function(x) { x - length(x) }
[1] -2 -1  0  1  2  3

Notice that length() is in itself a pre-supplied (i.e. Base) function. You can of course use a previously self-made function within another self-made function, as well as assign variables and perform other operations while spanning several lines:

vec2 <- (4:7)/2

msdf <- function(x, multiplier=4) {
    mult <- x * multiplier
    subl <- subtract.length(x)
    data.frame(mult, subl)

msdf(vec2, 5)
  mult subl
1 10.0 -2.0
2 12.5 -1.5
3 15.0 -1.0
4 17.5 -0.5

multiplier=4 makes sure that 4 is the default value of the argument multiplier, if no value is given when calling the function 4 is what will be used.

The above are all examples of named functions, so called simply because they have been given names (one, two, subtract.length etc.)