1

我有一个创建函数的构造函数。有一个名为“features”的变量是构造函数的本地变量,另一个名为“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并保留第一个声明,则程序也可以工作,并且在使用返回函数时更新第一个实例。在这种情况下,就返回的函数而言,两者都是自由变量。看来,返回函数内部是指在返回函数外部声明。一切都很好。featuresfeaturesfeaturesparamINfeaturesfeatures

这是我的具体问题:

3)但是如果我features[!paramIN] <- p按照给定的方式使用,但完全删除features <- paramIN,程序会失败,因为它找不到features. 似乎第一个声明(在返回的函数之外)是建立features一个二元向量所必需的。但是“内部”features是与“外部”不同的变量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
  } 
}
4

0 回答 0