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:
Syntax
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
greet <- function() {
cat("Hello from a function!\n")
}
greet()
greet()
Login to try C/C++/Java/PHP code in the editor
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
- Forgetting the parentheses when calling, such as
greet, which prints the function's code instead of running it. - Writing
function greet() { ... }as in other languages, when R needsgreet <- function() { ... }. - 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: