Problem 1

Regress <- function(X,y) {
  
  #Standard LS formula
  
  b <- solve(t(X)%*%X) %*% (t(X)) %*% y
  
  print(b)
  
  #Residuals 
  
  e <- y - (X%*%b)
  
  #Estimate Sigma^2
  
  sigma_sqrd <- ((t(e)%*%e)/(nrow(X)-ncol(X)))
  
  sigma_sqrd_matrix <- matrix(sigma_sqrd, nrow=ncol(X),ncol=ncol(X))
  
  SE = sqrt(sigma_sqrd_matrix * solve(t(X)%*%X))
  
  #Standard errors are reported in the variance-covariance matrix
  
  print(SE)
  
}

##Problem 2 with created function

matrix_cars <- as.matrix(mtcars)

Int <- rep(1,nrow(matrix_cars))

matrix_int <- cbind(Int,matrix_cars)

Regress_1 = Regress((matrix_int[,c(1,3,5,7)]),matrix_int[,c(2)])
##           [,1]
## Int 38.7517874
## cyl -0.9416168
## hp  -0.0180381
## wt  -3.1669731
## Warning in sqrt(sigma_sqrd_matrix * solve(t(X) %*% X)): NaNs produced
##           Int       cyl         hp        wt
## Int 1.7868640       NaN 0.08548060       NaN
## cyl       NaN 0.5509164        NaN       NaN
## hp  0.0854806       NaN 0.01187625       NaN
## wt        NaN       NaN        NaN 0.7405759
summary(Regress_1)
##       Int               cyl               hp                wt        
##  Min.   :0.08548   Min.   :0.5509   Min.   :0.01188   Min.   :0.7406  
##  1st Qu.:0.51083   1st Qu.:0.5509   1st Qu.:0.03028   1st Qu.:0.7406  
##  Median :0.93617   Median :0.5509   Median :0.04868   Median :0.7406  
##  Mean   :0.93617   Mean   :0.5509   Mean   :0.04868   Mean   :0.7406  
##  3rd Qu.:1.36152   3rd Qu.:0.5509   3rd Qu.:0.06708   3rd Qu.:0.7406  
##  Max.   :1.78686   Max.   :0.5509   Max.   :0.08548   Max.   :0.7406  
##  NA's   :2         NA's   :3        NA's   :2         NA's   :3

##Problem 2 with lm function

lm_regression = lm(mpg ~ cyl + hp + wt, data=mtcars)

summary(lm_regression)
## 
## Call:
## lm(formula = mpg ~ cyl + hp + wt, data = mtcars)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -3.9290 -1.5598 -0.5311  1.1850  5.8986 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 38.75179    1.78686  21.687  < 2e-16 ***
## cyl         -0.94162    0.55092  -1.709 0.098480 .  
## hp          -0.01804    0.01188  -1.519 0.140015    
## wt          -3.16697    0.74058  -4.276 0.000199 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.512 on 28 degrees of freedom
## Multiple R-squared:  0.8431, Adjusted R-squared:  0.8263 
## F-statistic: 50.17 on 3 and 28 DF,  p-value: 2.184e-11

Problem 3

#Since I used the normal iid standard errors. All of the first 5 assumptions must hold for these standard errors to be unbiased. Which are linearity, full rank, exogenity of the independent variables, homoscedacity and nonautocorrelation, and Xs maybe random or not. 

##Problem 4

#The assumptions needed for the coeffecients to be causal are the same as above, but Xs need be ranbom.