函数,该函数从r中的X和y生成值beta的向量

函数,该函数从r中的X和y生成值beta的向量,r,R,我想写一个函数,从X和y生成一个beta值向量,我们得到 β=[(X^T)*X]^-1*(X^T)*y 我写了一个这样的代码,但它变成了错误 t(X)*X中的错误:不一致阵列 请帮我做这个 代码: set.seed(143) X您应该使用矩阵乘法的符号,即使用%*%而不是* 尝试: BetaEstimator您应该使用矩阵积%*%,而不是元素积*。另外,crossprod可以用来简化表达式,如下所示 BetaEstimator <- function(X, y) { solve(cro

我想写一个函数,从X和y生成一个beta值向量,我们得到

β=[(X^T)*X]^-1*(X^T)*y

我写了一个这样的代码,但它变成了错误 t(X)*X中的错误:不一致阵列

请帮我做这个

代码:

set.seed(143)

X您应该使用矩阵乘法的符号,即使用
%*%
而不是
*

尝试:


BetaEstimator您应该使用矩阵积
%*%
,而不是元素积
*
。另外,
crossprod
可以用来简化表达式,如下所示

BetaEstimator <- function(X, y) {
  solve(crossprod(X)) %*% crossprod(X, y)
}

BetaEstimator这里有一种使用QR分解的方法

BetaEstimator <- function(X, y) solve.qr(qr(X), y)

set.seed(143)
X <- cbind(rep(1,50), rnorm(50,0,1), rnorm(50,0,1))
y <- 3 + -4*X[,2] + 2*X[,3] + rnorm(50,0,1)

# compare with R's linear model    
fit <- lm.fit(X, y)

coef(fit)
#       x1        x2        x3 
# 3.101107 -3.976275  1.966437 

BetaEstimator(X, y)
#[1]  3.101107 -3.976275  1.966437
BetaEstimator
BetaEstimator <- function(X, y) {
  solve(crossprod(X)) %*% crossprod(X, y)
}
BetaEstimator <- function(X, y) solve.qr(qr(X), y)

set.seed(143)
X <- cbind(rep(1,50), rnorm(50,0,1), rnorm(50,0,1))
y <- 3 + -4*X[,2] + 2*X[,3] + rnorm(50,0,1)

# compare with R's linear model    
fit <- lm.fit(X, y)

coef(fit)
#       x1        x2        x3 
# 3.101107 -3.976275  1.966437 

BetaEstimator(X, y)
#[1]  3.101107 -3.976275  1.966437