O'Reilly logo

Data Analysis with R - Second Edition by Tony Fischetti

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required