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

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:

  1. Function Arguments
Syntax
r
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

markup
greet <- function(name, times) {
  for (i in 1:times) {
    cat("Hello,", name, "!\n")
  }
}

greet("Sam", 2)
greet(times = 1, name = "Priya")
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 a required argument, such as calling greet("Sam") with no times, which errors only when times is used.
  2. Passing arguments in the wrong order without names, such as greet(2, "Sam"), which uses 2 as the name.
  3. 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:

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.