Writing Custom Functions

You can write your own custom functions in R. Here’s how you do it:

myfunction <- function(x, y) {

z <- x+y

return(z)

}

The term “myfunction” is the name of the function, and it can be anything you want. The “<- function()” part needs to stay exactly as shown, except for the contents of the parentheses. The x and y in the parentheses are called arguments, and there can be any number of these, separated by commas. In this case, the function takes two arguments. These arguments can be any kind of structure in R, from single numbers to huge matrices. The z <- x+y statement is the body of the function, where the function performs its tasks. In this case, it just adds the two numbers. Finally, return(z) returns the value of z to the user. A function can only return one thing, but that thing can be any kind of data structure.

You can save your function in a script and run the script to make the function available to your current R session. To run the above function, you would just type:

myfunction(4,5)

It would return the sum of the two numbers (in this case 9).

 

Advertisements