代码之家  ›  专栏  ›  技术社区  ›  gfgm

从函数内的np包调用函数困难,可能是环境问题

r
  •  0
  • gfgm  · 技术社区  · 7 年前

    我想用 npreg() 函数来自 np

    是用于非参数回归的函数。我分两个步骤进行估计,首先我估计带宽使用 npregbw() npreg() 在估计带上得到回归估计。在函数调用之外,我没有遇到任何问题。但是,在函数内部调用 npreg() 函数似乎无法与估计的带宽一起工作。下面是Reprex:

    x <- rnorm(20)
    y <- 2*x + rnorm(20)
    df <- data.frame(y, x)
    
    pidtest <- function(outformula, data) {
    
      # estimate conditional density of outcome 
      np_lower_bw <- np::npregbw(outformula, data = data)
      np_lower <- np::npreg(np_lower_bw)
      np_lower
    }
    
    pidtest(y~x, df)
    
    #> Error in eval(predvars, data, env): invalid 'envir' argument of type 'closure'
    

    如果我调用函数只是为了估计带宽,那就没有问题了

    pidtest <- function(outformula, data) {
    
      # estimate conditional density of outcome 
      np_lower_bw <- np::npregbw(outformula, data = data)
      # np_lower <- np::npreg(np_lower_bw)
      # np_lower
      np_lower_bw
    }
    
    pidtest(y~x, df)
    
    #> 
    #> Regression Data (20 observations, 1 variable(s)):
    #> 
    #>                       x
    #> Bandwidth(s): 0.3770171
    #> 
    #> Regression Type: Local-Constant
    #> Bandwidth Selection Method: Least Squares Cross-Validation
    #> Formula: y ~ x
    #> Bandwidth Type: Fixed
    #> Objective Function Value: 1.469502 (achieved on multistart 1)
    #> 
    #> Continuous Kernel Type: Second-Order Gaussian
    #> No. Continuous Explanatory Vars.: 1
    

    同样,在函数调用之外也没有问题:

    bws <- np::npregbw(y~x, df)
    np::npreg(bws)
    
    Regression Data: 20 training points, in 1 variable(s)
                         x
    Bandwidth(s): 0.307494
    
    Kernel Regression Estimator: Local-Constant
    Bandwidth Type: Fixed
    
    Continuous Kernel Type: Second-Order Gaussian
    No. Continuous Explanatory Vars.: 1
    

    我不知道为什么这个错误会出现在我的函数调用中,也不知道如何避免它。我想把这个估计嵌入到一个正在做其他事情的函数中,所以我急切地想找出一个方法使它工作。

    0 回复  |  直到 7 年前
        1
  •  2
  •   LocoGris    7 年前

    我无法解释确切原因,但如果您尝试这段代码,它会起作用:

    x <- rnorm(20)
    y <- 2*x + rnorm(20)
    df <- data.frame(y, x)
    
    pidtest <- function(outformula, data) {
    
      # estimate conditional density of outcome 
    
      np_lower_bw <- np::npregbw(as.formula(outformula), data = data)
      np_lower <- np::npreg(np_lower_bw)
      np_lower
    }
    
    pidtest("y~x", df)
    

    有关此主题的详细信息,请参阅此处: https://stat.ethz.ch/pipermail/r-help/2005-March/067109.html