【问题标题】:Warning message in R function for Multiple Linear Regression多元线性回归的 R 函数中的警告消息
【发布时间】:2020-05-12 20:21:46
【问题描述】:

我正在为一个主题的最终工作做一个用于多重线性回归的 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)

我该如何解决这个问题?我认为系数很好,但这个警告让我很困扰。

谢谢!

【问题讨论】:

  • length(x) 与矩阵的prod(dim(x)) 相同,而我假设您想要nrow(x)。我会将cbind(rep(1,length(x)),x) 更改为cbind(1, x),因为nrow(x) 对于向量会失败,但cbind(1, x) 可以处理简单回归和多元回归

标签: r linear-regression


【解决方案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

【讨论】:

    猜你喜欢
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 2014-01-30
    • 1970-01-01
    • 2022-08-20
    • 2016-12-19
    相关资源
    最近更新 更多