如何从 penalized 包中导出 penlized 回归模型的所有系数?需要它们来报告滚动回归估计

How to export all coefficients of a penlized regression model from package `penalized`? Need them for reporting rolling regression estimate

我已经能够 运行 将一些系数限制在正区域进行回归,但我在遇到问题时进行了很多滚动回归。这是我的示例代码:

library(penalized)
set.seed(1)
x1=rnorm(100)*10
x2=rnorm(100)*10
x3=rnorm(100)*10
y=sin(x1)+cos(x2)-x3+rnorm(100)

data <- data.frame(y, x1, x2, x3)

win <- 10

coefs <- matrix(NA, ncol=4, nrow=length(y))

for(i in 1:(length(y)-win)) {
  d <- data[(1+i):(win+i),]
  p <- win+i
  # Linear Regression
  coefs[p,] <- as.vector(coef(penalized(y, ~ x1 + x2 + x3, ~1, 
                                      lambda1=0, lambda2=0, positive = c(F, F, T), data=data)))}

这就是我通常使用滚动回归系数填充矩阵的方式,现在我收到错误:

Error in coefs[p, ] <- as.vector(coef(penalized(y, ~x1 + x2 + x3, ~1,  : 
  number of items to replace is not a multiple of replacement length

我假设产生此错误是因为该惩罚回归函数并不总是出现 Intercept + 3 系数。有没有办法让 penalized 函数也显示 0 系数?或其他填充矩阵的方式 / data.frame?

也许您不知道 which 对象 coefwhich 参数。看看:

getMethod(coef, "penfit")

#function (object, ...) 
#{
#    .local <- function (object, which = c("nonzero", "all", "penalized", 
#        "unpenalized"), standardize = FALSE) 
#    {
#        coefficients(object, which, standardize)
#    }
#    .local(object, ...)
#}
#<environment: namespace:penalized>

我们可以设置which = "all"来报告所有系数。默认值为 which = "nonzero",这会导致 "replacement length differs" 问题。

以下作品:

library(penalized)
set.seed(1)
x1 = rnorm(100)*10
x2 = rnorm(100)*10
x3 = rnorm(100)*10
y = sin(x1) + cos(x2) - x3 + rnorm(100)

data <- data.frame(y, x1, x2, x3)

win <- 10

coefs <- matrix(NA, ncol=4, nrow=length(y))

for(i in 1:(length(y)-win)) {
  d <- data[(1+i):(win+i),]
  p <- win + i
  pen <- penalized(y, ~ x1 + x2 + x3, ~1, lambda1 = 0, lambda2 = 0,
                   positive = c(F, F, T), data = data)
  beta <- coef(pen, which = "all")
  coefs[p,] <- unname(beta)
  }