Writing Your Own Functions in R
Interactive beginner R tutorial on writing functions: function(){}, arguments, default values, return(), and applying a function across values. Run real R in your browser.
The moment you copy-paste the same code twice, it’s time to write a function. Everything below is a live R console — edit the code and press Run Code.
Watch: writing your own functions
Defining a function, giving arguments default values, returning a result, and applying it across many values.
Download the R script · ▶ Practice in the playground — or edit and run each snippet below.
Your first function
function(args) { body }. Because R is vectorized, it works on one value or many for free:
Default argument values
Give an argument a default and the caller only supplies what they want to change:
Several steps, one result
Do the work, then hand back a value with return():
Functions + apply = power
Run your function across a whole set of inputs with the apply family:
Your turn
Next: Installing & loading packages → — extending R beyond base.