[英]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: 我想要实现的是从其父级中的嵌套函数中分配一个值(使用
assign
函数,我已经读到使用<<-
可能很危险),并在其中使用它:
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
. 在使用
y
计算之前,需要运行f1()
。 x
argument of assign
function takes character. assign
函数的x
参数采用字符。
myfun <- function(m) {
f1 <- function() {
assign(x = "y", value = 2, envir = parent.frame())
}
f1()
m*3*y
}
myfun(5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.