HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to RVariablesData TypesOperatorsCharacters (character)VectorsConditions (if / else)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ Character
📚 Vector
🔀 Condition & Loop
🧩 Function
R›Functions

Functions

Definition with function, parameters, return (or last expression) and calling.

Simple enough for a 5-year-old to understand

Define a function

defined with function and assigned to a variable. The last expression is returned automatically.

Example code
1
square <- function(x) {
Function that takes x.
FunctionFunction that takes x.
2
return(x * x)
Returns the result.
DefinitionReturns the result.
3
}
4
cat(square(5), "\n", sep="")
25
Output / Input25
FunctionDefinitionOutput / Input
💡 Hint: return(x) has parentheses; or the last expression is returned automatically.

About this topic

In R, a function is also a value: it is created with the function keyword and assigned to a variable. This makes passing functions as arguments to other functions natural and forms the basis of the apply family.

R functions have two distinctive features. First, the last evaluated expression is returned automatically; writing return is not mandatory. Second, arguments are evaluated lazily: if an argument is not used, it is never calculated.

Arguments can be given by name or by position; even partial name matching works. This flexibility is convenient, but for readability, it is a good habit to provide at least all arguments after the first few by name.

What you will learn

  • Defining and calling a function
  • Default arguments
  • Implicit return and explicit return
  • Scope rules
  • Passing arguments by name

Who is this for?

  • Those who want to make analysis code reusable
  • Learners of the apply family
  • Those trying to modify variables inside a function

When to use?

If you are going to apply the same analysis step to different datasets, extracting it into a function is mandatory; copied code drifts apart over time.

Functions are the most effective way to keep report-generating scripts readable: the details stay inside the function, and the script only shows the steps.

Common mistakes

Wrong

topla <- function(a, b) {
  a + b
}
print(topla(5))

The second argument was not provided and has no default value; R throws the "argument \"b\" is missing, with no default" error. The interesting part is: the error does not appear at the moment of the call, but at the exact moment b is first used, because arguments are evaluated lazily.

Correct

topla <- function(a, b = 0) {
  a + b
}
print(topla(5))

Wrong

sayac <- 0
artir <- function() {
  sayac <- sayac + 1
}
artir()
print(sayac)

Assignment inside the function creates a local copy; the outside variable remains unchanged and zero is still printed to the screen. R's scoping rule allows reading but keeps writing local. The correct approach is to return the value and assign it outside.

Correct

sayac <- 0
artir <- function(deger) {
  deger + 1
}
sayac <- artir(sayac)
print(sayac)

Wrong

ortalama_al <- function(v) {
  toplam <- sum(v)
  adet <- length(v)
}
print(ortalama_al(c(1, 2, 3)))

The final expression is an assignment, and the value of an assignment is returned invisibly; nothing is printed to the screen instead of the expected average. In R, a function returns the last evaluated expression, so the last line needs to actually be the value you want.

Correct

ortalama_al <- function(v) {
  toplam <- sum(v)
  adet <- length(v)
  toplam / adet
}
print(ortalama_al(c(1, 2, 3)))

Frequently asked questions

Do I need to write return?

It is not mandatory; the last expression is returned automatically. Still, return is necessary when you want to exit early from the middle of a function, and writing it explicitly may be preferred in long functions as it clarifies intent.

What does lazy evaluation mean?

An argument is evaluated the moment it is first used inside the function; if it is never used, it is never calculated. This saves you from performing expensive calculations unnecessarily, but it also causes error messages to pop up in unexpected places.

How to return multiple values?

By returning a list. In R, a function returns a single object, but that object can be a list holding multiple values inside. The calling side accesses the elements by their names; this is the standard way for multiple returns.

Summary

Functions are created with function and assigned to a variable.

The last evaluated expression is returned automatically.

Arguments are evaluated lazily.

Assignment inside the function does not change the outside.

Multiple values are returned via a list.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code