簡體   English   中英

無法從函數內的np包調用函數,可能是環境問題

[英]difficulty calling a function from np package within a function, possible environment issue

我正在嘗試在另一個函數中使用np包中的npreg()函數。 我遇到與環境有關的錯誤。

npreg()是用於非參數回歸的函數。 我分兩步進行估算,首先使用npregbw()估算帶寬,然后可以在估算的帶寬上調用npreg()以獲得回歸估算。 在函數調用之外,我沒有遇到任何問題。 但是,在函數內部調用npreg()函數似乎無法使用估計的帶寬。 重新說明如下:

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

我無法弄清楚為什么此錯誤會在函數調用內發生,也無法解決。 我想將此估算值嵌入正在執行其他操作的函數中,因此急於想出一種使之起作用的方法。

我無法確切解釋原因,但是如果您嘗試這段代碼,它會起作用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM