Writing a function in R

Most of the tasks in R are performed using functions. A function in R has the same utility as functions in Arithmetic.

Getting ready

In order to write a simple function in R, we must first open a new R script by navigating to File | New file.

How to do it…

We write a very simple function that accepts two values and adds them together. Copy and paste the code in the new blank R script:

add = function (x,y){
  x+y
}

How it works…

A function in R should be defined by function(). Once we define our function, we need to save it as a .r file. Note that the name of the file should be the same as the function; hence we save our function with name add.r.

In order to use the add() function in the R command window, we need to source the file ...

Get R: Recipes for Analysis, Visualization and Machine Learning 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.