简体   繁体   中英

R: assign a value in a upper-level function

Probably a simple question, but I can't figure it out myself, working with environments and scoping still confuse me.

I have a function, nested in a function. What I am trying to achieve is to assign a value (using the assign function, I have read that using <<- can be dangerous) from the nested function in its parent and use it there:

myfun <- function(m) {
  m*3*y
  f1 <- function() {
    assign(x = y, value = 2, envir = parent.frame())
  }
  f1()
}

However, error is returned:

Error in myfun(m = 5) : object 'y' not found

In addition, what if I have a function, nested in a function, nested in a function, nested in a function, etc., and I want to choose in which upper level to assign the value from the lowest level function?

Two points. You need to run f1() before you compute with y . x argument of assign function takes character.

myfun <- function(m) {
  f1 <- function() {
  assign(x = "y", value = 2, envir = parent.frame())
  }
  f1()
  m*3*y
}

myfun(5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM