[英]Warning message in R function for Multiple Linear Regression
我正在做一個 R package 用於一個主題的最終工作,我已經開始計算線性回歸系數。
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)
我怎樣才能解決這個問題? 我認為系數很好,但這個警告讓我很困擾。
謝謝!
讓我們考慮一下 function 中的第一行:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.