Functions in R Programming Language

Functions are central in R. We’ll learn about functions with a few different examples.

# Here's a function that takes two numbers and returns their sum
plus <- function(a, b) {
  return(a + b)
}

# In R, the last expression in a function is automatically returned,
# so we could also write the function like this:
plus_implicit <- function(a, b) {
  a + b
}

# Here's a function that takes three parameters and returns their sum
plus_plus <- function(a, b, c) {
  return(a + b + c)
}

# Main execution
main <- function() {
  # Call a function just as you'd expect, with name(args)
  res <- plus(1, 2)
  print(paste("1+2 =", res))

  res <- plus_plus(1, 2, 3)
  print(paste("1+2+3 =", res))
}

# Run the main function
main()

To run the program, save it as functions.R and use Rscript:

$ Rscript functions.R
1+2 = 3
1+2+3 = 6

In R, functions are first-class objects, which means they can be assigned to variables, passed as arguments to other functions, and returned from functions.

R uses lexical scoping, which means that free variables in a function are looked up in the environment where the function was defined.

Unlike some other languages, R doesn’t require you to declare the types of function parameters or return values. This makes R more flexible but also means you need to be more careful about type consistency in your code.

R also supports default arguments, variable number of arguments, and named arguments, which we’ll explore in later examples.

There are several other features to R functions. One is the ability to return multiple values using lists or data frames, which we’ll look at next.