panman panman - 14 days ago 7
R Question

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?

Answer

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)