Functions

If we need to perform some computation that isn't already a function in R a multiple number of times, we usually do so by defining our own functions. A custom function in R is defined using the following syntax:

  function.name <- function(argument1, argument2, ...){
    # some functionality
  }

For example, if we wanted to write a function that determined if a number supplied as an argument was even, we can do so in the following manner:

  > is.even <- function(a.number){
  +   remainder <- a.number %% 2
  +   if(remainder==0)
  +     return(TRUE)
  +   return(FALSE)
  + }
  >
  > # testing it
  > is.even(10)
  [1] TRUE
  > is.even(9)
  [1] FALSE

As an example of a function that takes more than one argument, let's generalize the preceding function by creating a function that ...

Get R: Data Analysis and Visualization now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.