Menu
Coddy logo textTech

Default Parameter Values

Part of the Fundamentals section of Coddy's R journey — lesson 51 of 78.

Sometimes you want a function to have a "standard" behavior that can be customized when needed. Default parameter values let you define what a parameter should be if the caller doesn't provide it.

You set a default value by using = in the function definition:

greet <- function(name = "Guest") {
  print(paste("Hello,", name))
}

greet()
greet("Alice")

Output:

[1] "Hello, Guest"
[1] "Hello, Alice"

When called without an argument, the function uses "Guest" as the default. When you provide a value, it overrides the default.

You can mix required and optional parameters. Parameters with defaults should come after those without:

calculate_total <- function(price, tax_rate = 0.1) {
  return(price + (price * tax_rate))
}

print(calculate_total(100))
print(calculate_total(100, 0.2))

Output:

[1] 110
[1] 120

Here, price is required while tax_rate defaults to 10%. This makes your functions flexible - simple to use in common cases, but customizable when needed.

challenge icon

Challenge

Easy

Create a function called calculate_shipping that takes two arguments:

  • weight - the weight of the package (required)
  • rate - the cost per unit of weight (optional, defaults to 5)

The function should return the shipping cost, calculated as weight * rate.

You will receive two lines of input:

  1. A weight value
  2. Either a rate value OR the word default

If the second input is default, call the function with only the weight (using the default rate). Otherwise, call the function with both the weight and the provided rate.

Print the returned result.

For example, if the inputs are:

10
default

The output should be:

[1] 50

If the inputs are:

10
3

The output should be:

[1] 30

Cheat sheet

You can set default parameter values in a function using = in the function definition:

greet <- function(name = "Guest") {
  print(paste("Hello,", name))
}

greet()           # Uses default: "Hello, Guest"
greet("Alice")    # Overrides default: "Hello, Alice"

When mixing required and optional parameters, place parameters with defaults after those without:

calculate_total <- function(price, tax_rate = 0.1) {
  return(price + (price * tax_rate))
}

calculate_total(100)       # Uses default tax_rate: 110
calculate_total(100, 0.2)  # Custom tax_rate: 120

Try it yourself

# Read input
con <- file("stdin", "r")
weight <- as.numeric(suppressWarnings(readLines(con, n = 1)))
rate_input <- suppressWarnings(readLines(con, n = 1))
close(con)

# TODO: Write your code below
# 1. Define the calculate_shipping function with weight (required) and rate (optional, default = 5)
# 2. Check if rate_input is "default" or a number
# 3. Call the function appropriately and print the result
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals