[英]function that generates a vector of values beta from X and y in r
I would like to write a function that generates a vector of values of beta from X and y, we get我想写一个 function 从 X 和 y 生成一个 beta 值向量,我们得到
beta = [(X^T)*X]^-1 * (X^T) * y贝塔 = [(X^T)*X]^-1 * (X^T) * y
I Wrote a code as this, but it turns error as Error in t(X) * X: non-conformable arrays我这样写了一个代码,但它在 t(X) * X: non-conformable arrays 中变成了错误
please help me with this.请帮我解决一下这个。
code:代码:
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)
BetaEstimator <- function(X, y){
Beta <- solve(t(X)*X) * t(X) * y
return(Beta)}
BetaEstimator(X,y)
You should use the notation for matrix multiplication, that is, use %*%
instead of *
.您应该使用矩阵乘法的符号,即使用
%*%
而不是*
。
Try:尝试:
BetaEstimator <- function(X, y) {
solve(t(X) %*% X) %*% t(X) * y
}
You should use matrix product %*%
, rather than element-wise product *
.您应该使用矩阵产品
%*%
,而不是元素产品*
。 Also, crossprod
can be used to simplify your expression, like below此外,
crossprod
可用于简化您的表达式,如下所示
BetaEstimator <- function(X, y) {
solve(crossprod(X)) %*% crossprod(X, y)
}
Here is a way using the QR decomposition.这是一种使用 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
The coefficients are equal to R's.系数等于 R。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.