← Back to R Course | Chapter 5: Functions | Lesson 1 of 7

Function Basics

A function is a named recipe you write once and use again and again. You give it a name, list the steps, and call it whenever you need it.

In this page:

  1. Function Basics
Syntax
r
function_name <- function(arg1, arg2) {
  # body
  result
}

function_name(value1, value2)

Function Basics

A function in R is created with function(args) { body } and assigned to a name like any other value, since functions are first-class objects in R.

Calling it looks just like calling any built-in function. Breaking logic into functions is the primary way to organize and reuse R code.

Note: Functions are ordinary values in R -- you can pass them as arguments to other functions, just like numbers or strings.

Example: Function Basics

markup
greet <- function() {
  cat("Hello from a function!\n")
}

greet()
greet()
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the parentheses when calling, such as greet, which prints the function's code instead of running it.
  2. Writing function greet() { ... } as in other languages, when R needs greet <- function() { ... }.
  3. Defining a function after the code that calls it in a script, so the call fails with could not find function.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.