Function Arguments
Arguments are the ingredients you hand to a function each time you use it, like the flavor and size when ordering an ice cream. You can pass them in order or by name.
In this page:
Syntax
function_name <- function(arg1, arg2) {
# body
}
function_name(value1, value2) # by position
function_name(arg2 = value2, arg1 = value1) # by name
Function Arguments
Arguments are declared in the function's parameter list and can be passed either positionally or by name at the call site.
Named arguments can be given in any order, which is especially useful for functions with many parameters. Mixing positional and named arguments is allowed, as long as positional ones come first.
Note:
Calling with named arguments, like f(name = "Sam", times = 3), is more readable and order-independent.
Example: Function Arguments
greet <- function(name, times) {
for (i in 1:times) {
cat("Hello,", name, "!\n")
}
}
greet("Sam", 2)
greet(times = 1, name = "Priya")
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 a required argument, such as calling
greet("Sam")with notimes, which errors only whentimesis used. - Passing arguments in the wrong order without names, such as
greet(2, "Sam"), which uses2as the name. - Misspelling a named argument like
greet(nam = "Sam"), which may match partially or fail with an unused argument error.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: