如何在R中进行约束回归

g3l*_*3lo 5 regression r

假设我有一个简单的回归方程

lm(y~., newdata=df)

我知道如果我想把截距减少到0,我写

lm(y+0., newdata=df)

然而,有没有一种方法可以产生逐步回归,同时将每个系数限制在特定范围内?例如:

step(lm(y~.>1000, newdata=df)

上面的方法不起作用,但是有没有办法说生成一个基本上产生最佳拟合并强制每个系数大于 1,000 的回归?或者,小于指定范围。

#as per Gautam    
minfunc <- function(coefs){
      out <- sum(sapply(3:314, function(z) return(coefs[z]*test2[, z])))
      return(out)
    }


    par = c(1, 1, 30) # initial value
    lb = c(-1, -1, -300000) # lower bound for coefs
    ub = c(30, 30, 30000) # upper bound 

    result <- hjkb(par = par, fn = minfunc, lower = lb, upper = ub)
Run Code Online (Sandbox Code Playgroud)

谢谢你,

Gau*_*tam 2

这是一个应该可以工作的代码。您需要调整边界等才能得到您想要的。

library(data.table)
library(dfoptim)

minfunc <- function(coefs){
  # using mtcars as the sample data - you would read in your data here
  df <- as.data.table(mtcars)

  out <- (sum(coefs[1]*df$cyl + coefs[2]*df$wt + coefs[3]) - sum(df$mpg))^2
  return(out)
}


par = c(1, 1, 30) # initial value
lb = c(-1, -1, -300000) # lower bound for coefs
ub = c(30, 30, 30000) # upper bound 

result <- hjkb(par = par, fn = minfunc, lower = lb, upper = ub)
Run Code Online (Sandbox Code Playgroud)

比较lm

> lm(mpg ~ cyl + wt, data = mtcars)

Call:
lm(formula = mpg ~ cyl + wt, data = mtcars)

Coefficients:
(Intercept)          cyl           wt  
     39.686       -1.508       -3.191  

> result$par
[1]  0.00000 -1.00000 23.30788 
#        cyl       wt constant
Run Code Online (Sandbox Code Playgroud)

结果与预期不同。收敛和最终结果取决于优化算法的选择和初始输入。我用了hjkb一个例子,但它不是最好的算法。您可能想根据您的需要尝试不同的算法。