0
0
R Programmingprogramming~15 mins

Variable scope (lexical scoping) in R Programming - Mini Project: Build & Apply

Choose your learning style9 modes available
Variable scope (lexical scoping) in R
📖 Scenario: You are helping a friend understand how variables work inside and outside functions in R. This is important because sometimes variables inside a function can be different from those outside.
🎯 Goal: Build a small R script that shows how variable values change inside a function and how the outside variable stays the same. You will create a variable, write a function that uses a variable with the same name, and then print both to see the difference.
📋 What You'll Learn
Create a variable called number with the value 10
Write a function called change_number that creates a local variable number with value 5 and returns it
Call the function change_number and save its result in a variable called new_number
Print both number and new_number to show their values
💡 Why This Matters
🌍 Real World
Understanding variable scope helps avoid bugs when writing functions that use variables with the same names as outside variables.
💼 Career
Many programming jobs require writing clean functions that do not accidentally change important data outside their scope.
Progress0 / 4 steps
1
Create the initial variable
Create a variable called number and set it to 10.
R Programming
Need a hint?

Use the assignment operator <- to set the value.

2
Write a function with a local variable
Write a function called change_number that creates a local variable number with value 5 and returns number.
R Programming
Need a hint?

Inside the function, create a variable number and use return() to send it back.

3
Call the function and save the result
Call the function change_number and save its result in a variable called new_number.
R Programming
Need a hint?

Use the function name with parentheses to call it and assign the result.

4
Print both variables to see the difference
Print the variables number and new_number using two separate print() statements.
R Programming
Need a hint?

Use print(number) and print(new_number) to show their values.