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] 120Here, 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
EasyCreate 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 to5)
The function should return the shipping cost, calculated as weight * rate.
You will receive two lines of input:
- A weight value
- 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
defaultThe output should be:
[1] 50If the inputs are:
10
3The output should be:
[1] 30Cheat 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: 120Try 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 resultThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values