0
0
R Programmingprogramming~20 mins

Variable scope (lexical scoping) in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Lexical Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested function with lexical scope
What is the output of this R code?
R Programming
x <- 10
f <- function() {
  x <- 20
  g <- function() {
    x
  }
  g()
}
f()
A[1] 20
B[1] 10
CError: object 'x' not found
D[1] NULL
Attempts:
2 left
💡 Hint
Remember that inner functions use variables from their defining environment unless shadowed.
Predict Output
intermediate
2:00remaining
Value of variable after function call
What is the value of x after running this code?
R Programming
x <- 5
foo <- function() {
  x <- 10
}
foo()
x
A[1] 10
B[1] 5
CNULL
DError: object 'x' not found
Attempts:
2 left
💡 Hint
Does the function foo() change the global x or only a local copy?
Predict Output
advanced
2:00remaining
Output of function modifying global variable with <<-
What is the output of this code?
R Programming
x <- 1
modify <- function() {
  x <<- 2
}
modify()
x
ANULL
B[1] 1
CError: object 'x' not found
D[1] 2
Attempts:
2 left
💡 Hint
The <<- operator assigns to a variable in the parent environment.
Predict Output
advanced
2:00remaining
Error caused by variable scope in nested functions
What error does this code produce?
R Programming
outer <- function() {
  inner <- function() {
    y
  }
  inner()
}
outer()
AError: object 'y' not found
BNULL
C[1] 0
D[1] NA
Attempts:
2 left
💡 Hint
Is y defined anywhere in the function or global environment?
🧠 Conceptual
expert
3:00remaining
How many variables are in the environment after execution?
Consider this code. How many variables are in the environment of function f after it runs?
R Programming
f <- function() {
  a <- 1
  b <- 2
  g <- function() {
    c <- 3
    a + b + c
  }
  g()
}
A4 variables: a, b, c, and g
B3 variables: a, b, and c
C2 variables: a and b
D1 variable: g
Attempts:
2 left
💡 Hint
Variables inside g() exist only during g() execution, not in f()'s environment after g() finishes.