我已经能够运行回归,其中一些系数被约束到正区域,但我在面对问题的时候做了很多滚动回归。这是我的示例代码:
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)))}
这就是我通常用滚动回归中的coefs填充矩阵的方法,现在我收到错误:
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的其他方式?
答案 0 :(得分:3)
也许你不知道“{1}} {for}”对象的which
参数。看看:
coef
我们可以设置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"