0
0
R Programmingprogramming~15 mins

Default argument values in R Programming - Mini Project: Build & Apply

Choose your learning style9 modes available
Default argument values
📖 Scenario: Imagine you are creating a simple calculator function in R that adds two numbers. Sometimes, you want to add a number to zero by default if the second number is not given.
🎯 Goal: Build a function called add_numbers that adds two numbers, where the second number has a default value of 0.
📋 What You'll Learn
Create a function named add_numbers with two parameters: a and b
Set the default value of parameter b to 0
Return the sum of a and b
Call the function with one argument and print the result
Call the function with two arguments and print the result
💡 Why This Matters
🌍 Real World
Default argument values are useful in many programs where some inputs are optional or have common defaults, like setting a default tax rate or default color.
💼 Career
Understanding default arguments helps you write flexible and user-friendly functions, a key skill for software development and data analysis.
Progress0 / 4 steps
1
Create the function skeleton
Write a function named add_numbers with two parameters: a and b. Do not set any default values yet.
R Programming
Need a hint?

Use the function keyword to create a function with parameters a and b.

2
Set default value for second parameter
Modify the function add_numbers so that the parameter b has a default value of 0.
R Programming
Need a hint?

Set the default value by using b = 0 inside the function parameters.

3
Add the core logic to sum the numbers
Inside the function add_numbers, return the sum of a and b.
R Programming
Need a hint?

Use return(a + b) to send back the sum.

4
Test the function with one and two arguments
Call the function add_numbers with one argument 5 and print the result. Then call it with two arguments 5 and 3 and print the result.
R Programming
Need a hint?

Use print(add_numbers(5)) and print(add_numbers(5, 3)) to show the results.