Written and maintained by CASRAI Editorial Board
Last updated
A function in R programming is an R object that takes arguments, runs a block of code and returns a result. You create one with function(arglist) body, store it under a name, and call it like any built-in. This guide is for researchers and analysts who repeat the same analysis step and want to wrap it once, with working code, the lazy-evaluation rule that trips people up, and what %>% does. Facts below are from the R manuals (An Introduction to R and The R Language Definition, release 4.6.2 of 2026-10-29, read 2026-11-07).
What a function in R is used for in research
R’s manual states that functions are themselves objects that can be stored in the workspace, so a function you write behaves like any value you can name, pass and reuse. In research this means a repeated step (a standard error, a two-sample t statistic, a cleaning routine) lives in one place instead of being pasted across scripts, and a correction is made once. The manual’s own example is stdError <- function(x) sqrt(var(x)/length(x)). Wrapping steps this way also supports reproducibility: the same code is called for every dataset. For tabular inputs see data frames in R.
Install or access R
R is distributed by the R Project through CRAN (cran.r-project.org), which also hosts the manuals cited here. Install R from CRAN, start an R session and type the examples at the prompt, or save them in a script and run it. Functions you define in a session live in the workspace of that session.
Write your first function in R: step by step
- Choose a name and arguments. The syntax in the language definition is
function ( arglist ) body. Assign it to a name with<-. - Write the body in braces when it has more than one statement. The manual’s two-sample example does this and ends with the name of its result object:
twosam <- function(y1, y2) { n1 <- length(y1); n2 <- length(y2) yb1 <- mean(y1); yb2 <- mean(y2) s1 <- var(y1); s2 <- var(y2) s <- ((n1-1)*s1 + (n2-1)*s2)/(n1+n2-2) tst <- (yb1 - yb2)/sqrt(s*(1/n1 + 1/n2)) tst} - Call it with arguments by position or by name:
tstat <- twosam(c(5,6,7), c(3,4,5)); tstat. - Add defaults where sensible. The manual’s example is
fun1 <- function(data, data.frame, graph=TRUE, limit=20) { ... }, callable asfun1(d, df)orfun1(d, df, limit=10). - Keep assignments local. Ordinary assignments inside a function are local and lost on exit, so
X <- qr(X)in the manual’sbslash()does not change the caller’sX. Global changes need<<-orassign(), which the manual describes.
Output and how to read it
The call above prints the value of tst. With the three-value samples the means are 6 and 4, both variances 1, so the pooled variance is 1 and the statistic is 2 divided by sqrt(2/3), which prints as [1] 2.44949. A function returns one object, so the manual’s bdeff() returns a list (efficiency factors plus canonical contrasts) when several results are needed; extract parts with $.
Types of functions in R programming
There is no single official four-way list; one practical grouping, each tied to the language definition, is:
| Type | What it is, per the R manuals |
|---|---|
| User-defined (closure) | Created with function; its type name is "closure", described as “a function”. |
| Built-in and special (primitive) | Internal functions shown as .Primitive. Builtins evaluate their arguments; specials do not. is.primitive tells them apart from interpreted functions. |
| Anonymous | A function not given a name, “most frequently used as arguments to other functions such as the apply family or outer”. Example: (function(x) x^2)(5). |
| Generic (S3 methods) | “Generic functions are used to determine the appropriate method.” mean is one: function (x, ...) UseMethod("mean"). |
Many everyday statistical and math functions you call (mean, var, sqrt, length) appear in the manual’s examples; use help(name) or ?name to open any function’s help page.
Defaults, ... and lazy evaluation
Named arguments and defaults
Named arguments may be given in any order, after any leading positional ones. Defaults can be arbitrary expressions, including ones using other arguments. The language definition adds that default arguments are evaluated in the function’s own evaluation frame, while supplied arguments are evaluated in the caller’s frame.
Lazy evaluation
“Arguments are not evaluated until needed.” In this illustrative example (written for this guide to follow that rule), the default for n is evaluated only when n is first used, inside the function, after x has changed:
f <- function(x, n = length(x)) { x <- c(x, 0); n }f(1:3)[1] 4
A default of length(x) would give 3 if evaluated early; it gives 4 because it is evaluated late, in the function frame. Do not rely on arguments for side effects, because the manual notes there is no guarantee an argument will ever be evaluated.
The ... argument
Adding ... lets a function pass settings on to another, as many graphics functions do with par(). Inside, list(...) returns them as a named list and ..1, ..2 access them one at a time. See pch in R for one such plotting argument.
What %>% does in R
%>% is the pipe from the magrittr package, not base R. Its documentation says it pipes the left-hand side forward into the expression on the right: x %>% f is equivalent to f(x), and x %>% f %>% g %>% h equals h(g(f(x))). With magrittr loaded, c(1,4,9) %>% sqrt %>% sum returns 6. The R language definition also lists a base operator |> in its operator precedence table, at the same level as user-defined %xyz% operators. The manual’s section on binary operators shows why %>% is itself an ordinary function: any function named %anything% can be used as a binary operator, as %*% and %o% are.
Troubleshooting
- “could not find function”: the name is misspelled or the package that provides it is not loaded.
%>%needs magrittr attached. - “unused argument”: the call supplies an argument the function’s formal list does not have. Check names against the definition, since named arguments are matched to formals before positional ones.
- “object not found”: a variable used in the body does not exist in the function, caller or workspace. Assignments inside a function are local, so a result created there is not visible outside unless returned.
- Result missing after the call: the function must end with the object you want (as
tstabove) or return a list.
Free alternatives for writing functions
| Language | How a function is defined (official docs) |
|---|---|
| R | name <- function(args) body (R Language Definition) |
| Python | “The keyword def introduces a function definition”; lambda a, b: a+b makes a small anonymous function (Python tutorial, section 4) |
| Julia | f(x, y) = x + y compact form; functions are first-class objects and can be anonymous, x -> x^2 + 2x - 1 (Julia manual, Functions) |
For the MATLAB equivalent see anonymous functions in MATLAB and the comparison MATLAB vs R; for another package workflow in R see clusterProfiler.
FAQ
What are the four types of functions in R?
The R manuals do not number them; a practical grouping is user-defined closures, built-in/special primitives, anonymous functions and generic functions that dispatch methods with UseMethod. See the table above.
Is R becoming outdated?
Evidence here is limited to currency: the R manuals on CRAN describe R version 4.6.2, dated 2026-10-29, so the language is still being released. This page makes no claim about popularity.
What does %>% do in R?
It passes the left-hand value into the function on the right, so x %>% f equals f(x) (magrittr).
What are the 7 basic functions?
The R manuals define no official list of seven. The functions their introductory examples lean on include length, mean, var and sqrt, plus c() for combining values.
Sources
- R Core Team, An Introduction to R (release 4.6.2, 2026-10-29), sections 2.8, 4.2, 10; read 2026-11-07.
- R Core Team, The R Language Definition, sections 2.1.7, 4.1, 4.3, 5, 10.4; read 2026-11-07.
- magrittr documentation; read 2026-11-07.
- Python tutorial, Defining Functions and Julia manual, Functions; read 2026-11-07.







