0
0
R Programmingprogramming~10 mins

Environment and closures in R Programming - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a function that returns another function adding a fixed number.

R Programming
makeAdder <- function(x) {
  function(y) {
    return(y [1] x)
  }
}
Drag options to blanks, or click blank then click option'
A+
B-
C*
D/
Attempts:
3 left
šŸ’” Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Forgetting to use the operator between y and x.
2fill in blank
medium

Complete the code to assign a value to a variable in the parent environment inside a closure.

R Programming
counter <- function() {
  count <- 0
  function() {
    count [1] count + 1
    return(count)
  }
}
Drag options to blanks, or click blank then click option'
A->
B=
C<-
D<<-
Attempts:
3 left
šŸ’” Hint
Common Mistakes
Using <- which creates a new local variable instead of updating the parent.
Using = which does not assign in the parent environment.
3fill in blank
hard

Fix the error in the closure that tries to access a variable from the wrong environment.

R Programming
makeMultiplier <- function(factor) {
  function(x) {
    return(x * [1])
  }
}

mult2 <- makeMultiplier(2)
mult2(5)
Drag options to blanks, or click blank then click option'
Afactor
Bx
CmakeMultiplier
Dmult2
Attempts:
3 left
šŸ’” Hint
Common Mistakes
Using x instead of factor inside the return statement.
Using the function names instead of variables.
4fill in blank
hard

Fill both blanks to create a closure that stores and retrieves a value.

R Programming
makeStorage <- function() {
  value <- NULL
  list(
    set = function(x) {
      value [1] x
    },
    get = function() {
      return(value [2])
    }
  )
}
Drag options to blanks, or click blank then click option'
A<<-
Bvalue
Creturn
D<-
Attempts:
3 left
šŸ’” Hint
Common Mistakes
Using <- in set which creates a local variable.
Not returning the stored value in get.
5fill in blank
hard

Fill all three blanks to create a closure that counts how many times it has been called and returns the count.

R Programming
makeCounter <- function() {
  count <- 0
  function() {
    count [1] count + 1
    return([2])
  }
}

counter <- makeCounter()
counter()
counter()  # returns [3]
Drag options to blanks, or click blank then click option'
A<-
Bcount
C<<-
D2
Attempts:
3 left
šŸ’” Hint
Common Mistakes
Using <- which does not update the parent variable.
Returning a literal number instead of the count variable.
Incorrect expected return value after two calls.