我有一个创建函数的构造函数。有一个名为' features'的变量。这是构造函数的局部变量,另一个名为'的变量是'这是构造函数创建的函数的本地。这些在下面的代码中区分为:
1)## --> 'features' assignment 1 (see question)
features <- paramIN
2)## --> 'features' assignment 2 (see question)
features[!paramIN] <- p
三个观察结果;
1)如果我在返回的函数内但features <- paramIN
之前移动features[!paramIN] <- p
,程序也可以。这是有道理的,因为paramIN
是返回函数内的自由变量,features
是返回函数的本地变量,features <- paramIN
在它是子集并分配之前声明并初始化features
2)如果我使用features[!paramIN] <<- p
并在返回的函数之外保留features
的第一个声明,程序也可以工作,而且,当features
的第一个实例更新时使用返回的函数。在这种情况下,就返回的函数而言,features
和paramIN
都是自由变量。看来返回函数内的features
引用在返回函数之外声明的features
。一切都很好。
这是我的具体问题:
3)但是如果我使用features[!paramIN] <- p
,但完全删除features <- paramIN
,程序将失败,因为它找不到features
。似乎第一个声明(在返回函数之外)是将features
建立为两元素向量所必需的。但是内心的&#39; features
是一个与外部&#39;不同的变量。 features
;它是返回函数的局部函数,那么它的存在和结构如何通过返回函数之外的features
声明来确定?
## make.Function
## ============
## Constructor to make a function that accepts a vector of one or two elements
## Input argument:
##
## paramIN: 2-element vector to initialize and subset'features'
## There are two instances of 'features':
## One is local to make.Function(), and the second is local to the function defined inside make.Function()
##
## Acceptable values for paramIN:
## paramIn=c(<double>,FALSE): The constructed function accepts
## a scalar double and assigns it to 'features[1]'
## paramIn=c(FALSE,<double>): The constructed function accepts
## a scalar double and assigns it to 'features[2]'
## paramIn=c(FALSE,FALSE): The constructed function accepts
## a 2-element vector of doubles and assigns it to 'features' -OR -
## The constructed function accepts
## a scalar double and assigns it to both elements of 'features'
make.Function <- function(paramIN=c(FALSE,FALSE)) {
## 'paramIN', and 'features' are local variables in make.Function
## --> 'features' assignment 1 (see question)
features <- paramIN
## This function is returned by make.Function
function(p) {
## --> 'features' assignment 2 (see question)
features[!paramIN] <- p
x <- features[1]
y <- features[2]
## This is a simple function
x+2*y
}
}