0
0
R Programmingprogramming~5 mins

Default argument values in R Programming

Choose your learning style9 modes available
Introduction

Default argument values let you give a function input a preset value. This means if you don't provide that input, the function still works using the default.

When you want a function to work even if some inputs are missing.
When most calls to a function use the same value for an argument.
When you want to simplify function calls for common cases.
When you want to avoid errors from missing arguments.
When you want to make your function easier to use by others.
Syntax
R Programming
function_name <- function(arg1 = default1, arg2 = default2) {
  # function body
}

Default values are set using the equals sign (=) inside the function definition.

If you call the function without that argument, the default is used automatically.

Examples
This function says hello. If you don't give a name, it uses "friend".
R Programming
greet <- function(name = "friend") {
  print(paste("Hello," , name))
}
This function adds two numbers. If you don't give y, it adds 10 by default.
R Programming
add <- function(x, y = 10) {
  return(x + y)
}
This function raises base to the exponent. If exponent is missing, it squares the base.
R Programming
power <- function(base, exponent = 2) {
  return(base ^ exponent)
}
Sample Program

This program shows three functions with default arguments. It calls each function twice: once with all arguments, once missing the defaulted argument.

R Programming
greet <- function(name = "friend") {
  print(paste("Hello," , name))
}

add <- function(x, y = 10) {
  return(x + y)
}

power <- function(base, exponent = 2) {
  return(base ^ exponent)
}

# Using greet with and without argument
  greet("Alice")
  greet()

# Using add with and without second argument
  print(add(5, 3))
  print(add(5))

# Using power with and without exponent
  print(power(3, 3))
  print(power(4))
OutputSuccess
Important Notes

Default arguments must come after arguments without defaults in the function definition.

You can use any valid R expression as a default value, like numbers, strings, or even other function calls.

Summary

Default argument values let functions work even if some inputs are missing.

They make functions easier and safer to use.

Set defaults by assigning values in the function definition.