Home > Software engineering >  How to assign a variable inside of an inner function to a variable in the outer function?
How to assign a variable inside of an inner function to a variable in the outer function?

Time:11-26

enter image description here

x <- function(){
number<- 10
   y <- function(){
     number <- 20
  }
y()
print(number)
}
x()

This code prints the value 10. How would I set the value of "number" within function "y ", so that it changes the value of "number" to 20 within function "x" and therefore prints the value 20, without assigning it to the global environment.

I tried to do this using the assign() function but I couldn't figure out what to set the parameter of "envir" to in order to achieve this e.g. assign("number", 20, envir = "whatever environment the of x is").

CodePudding user response:

Use parent.frame() (or rlang::caller_env()) to get the calling environment:

x <- function(){
  number<- 10
  y <- function() {
    assign("number", 20, envir = parent.frame())
  }
  y()
  print(number)
}
x()
# 20

Or use the <<- operator:

x <- function(){
  number<- 10
  y <- function() {
    number <<- 20
  }
  y()
  print(number)
}
x()

See this great answer by @Andrie for more on <<- (including cautions).

CodePudding user response:

Specify the previous environment and assign it to that environment

x <- function(){
number<- 10
   y <- function(env = parent.frame()){
     env$number <- 20
  }
 y()
print(number)
}

-testing

x()
[1] 20

CodePudding user response:

You could use this

x <- function(){
  number <- 10
  y <- function(){
    number <<- 20
  }
  y()
  print(number)
}
x()

This looks like an assignment to learn the scope of functions, you can return that internal 'number' value from 'y' function, and reassign 'number' to that value.

x <- function(){
  number <- 10
  y <- function(){
    number <- 20
    return(number)
    }
  number <- y()
  print(number)
}
x()
  • Related