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