简体   繁体   English

如何在R中手动获得最小二乘估计

[英]How to get least squares estimates by hand in R

I can't figure out how to get the least squares estimates (beta 1 hat and beta not hat) by hand using formulas instead of using functions. 我不知道如何使用公式而不是使用函数来手动获得最小二乘估计值(beta 1 hat和beta not hat)。

I have tried the formula below, I feel like I need to use a for loop but I just can't figure out how to do it. 我已经尝试过下面的公式,我觉得我需要使用一个for循环,但我只是想不出如何做。 Once I get beta 1 I should be able to get beta not. 一旦获得Beta 1,我应该就不会获得Beta。

x <- toluca$lot 
y <- toluca$work

beta1hat <- (sum(x[i]-mean(x)*sum(y[i] - mean(y))/sum(x[i]-mean(x)^2)

It says I is not defined but I don't know what I would define I as because it is a specific value within x. 它说我没有被定义,但是我不知道该怎么定义我,因为它是x中的特定值。

You can code the matrix form of the equation for the ordinary-least squares estimator in R. Here is an example: 您可以为R中的最小二乘估计量编写方程式的矩阵形式。这是一个示例:

set.seed(123)

x <- 1:10
a <- 2
b <- 3

y <- a*x + b + rnorm(10)

xm <- matrix(c(x, rep(1, length(x))), ncol = 2, nrow = 10)
ym <- matrix(y, ncol = 1, nrow = 10)

beta_hat <- MASS::ginv(t(xm) %*% xm) %*% t(xm) %*% ym

This gives exactly the same output as summary(lm(y ~ x)) . 这给出了与summary(lm(y ~ x))完全相同的输出。 Note, however, that the lm function is NOT a simple one liner because calculating the inverse of a matrix is a numerically challenging problem, so some precautions must be taken. 但是请注意, lm函数并不是一个简单的线性函数,因为计算矩阵的逆数是一个在数值上具有挑战性的问题,因此必须采取一些预防措施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM