R – Functions

What is a function?

In programming, a function is an organized and reusable set of instructions that perform a single focused action. The goal of a function is to reduce repetion and/or complexity.

Basic syntax

function_name <- function(argument) {
        instructions/code
}

Example

to_celcius <- function(f) {
        c <- (f-32) * 5/9
        print(paste(f, "degrees fahrenheit is", c, "degrees Celcius"))
}

Calling the function

> to_celcius(77)
[1] "77 degrees fahrenheit is 25 degrees Celcius"