1

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").

Ben_Roche
  • 13
  • 3
  • Use `<<-` instead of `<-` – Ric Nov 25 '22 at 18:13
  • 1
    Does this answer your question? [Global and local variables in R](https://stackoverflow.com/questions/10904124/global-and-local-variables-in-r) – Ric Nov 25 '22 at 18:15

3 Answers3

3

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).

zephryl
  • 14,633
  • 3
  • 11
  • 30
1

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
akrun
  • 874,273
  • 37
  • 540
  • 662
1

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()
Vida
  • 400
  • 2
  • 9