我正在做一个用于多线性回归的R包,以完成一个主题的最终工作,并且我已经开始计算线性回归系数。
AjusteLineal <- function(y,x){
x <- cbind(rep(1,length(x)),x)
return (solve(t(x) %*% x) %*% (t(x) %*% y))
}
x <- seq(0,30,5)
y <- c(2,1.41,1.05,0.83,0.7,0.62,0.57)
X <- cbind(x,x^2)
X
y
AjusteLineal(y,X)
这向我显示了警告。
[,1]
1.946904762
x -0.105571429
0.002038095
Warning message:
In cbind(rep(1, length(x)), x) :
number of rows of result is not a multiple of vector length (arg 1)
我该如何解决?我认为系数很好,但是这个警告使我感到困扰。
谢谢!
让我们考虑一下函数的第一行:
x <- cbind(rep(1,length(x)),x)
这正试图将列向量rep(1,length(x))
放在矩阵x
之前。相对于矩阵x
,该列向量将是什么样?让我们看看:
str(rep(1, length(X)))
# num [1:14] 1 1 1 1 1 1 1 1 1 1 ...
str(X)
# num [1:7, 1:2] 0 5 10 15 20 25 30 0 25 100 ...
# - attr(*, "dimnames")=List of 2
# ..$ : NULL
# ..$ : chr [1:2] "x" ""
矩阵的“长度”是矩阵中元素的数量;您不想在列向量前加上两个矩阵维的乘积长度!这就是为什么当您尝试该操作时会收到警告:
cbind(rep(1, length(X)), X)
# x
# [1,] 1 0 0
# [2,] 1 5 25
# [3,] 1 10 100
# [4,] 1 15 225
# [5,] 1 20 400
# [6,] 1 25 625
# [7,] 1 30 900
# Warning message:
# In cbind(rep(1, length(X)), X) :
# number of rows of result is not a multiple of vector length (arg 1)
幸运的是,我们可以在cbind()
中利用回收,因为您正在添加的列中只有一个值:
AjusteLineal <- function(y,x){
# x <- cbind(rep(1,length(x)),x) ## Causes warning
x <- cbind(1, x) ## works just fine
return (solve(t(x) %*% x) %*% (t(x) %*% y))
}
AjusteLineal(y,X)
# [,1]
# 1.946904762
# x -0.105571429
# 0.002038095