Like ive noted in my comment, you shuld use two independent variables. Moreover, I would like to sugest you the lapply
-function, which makes code more short, since you don't need the initialization/Storage part.
estimates_DT <- do.call("rbind",lapply(1:M, function(i) {
# Generate data
U_i = rnorm(n, mean = 0, sd = 2) # Error
X_i_1 = rnorm(n, mean = 5, sd = 5) # First independent variable
X_i_2 = rnorm(n, mean = 5, sd = 5) #Second ndependent variable
Y_i = beta_0 + beta_1*X_i_1 + beta_2*X_i_2 + U_i # Dependent variable
# Formulate data.table
data_i = data.table(Y = Y_i, X1 = X_i_1, X2 = X_i_2)
# Run regressions
ols_i <- fixest::feols(data = data_i, Y ~ X1 + X2)
ols_i$coefficients
}))
estimates_DT <- setNames(data.table(estimates_DT),c("beta_0","beta_1","beta_2"))
To compare the predictions of the two cars, define the following function taking the two carnames you want to comapre as arguemnt:
compareCarEstimations <- function(carname1="Mazda RX4",carname2="Datsun 710") {
car1data <- mtcars[rownames(mtcars) == carname1,c("cyl","hp")]
car2data <- mtcars[rownames(mtcars) == carname2,c("cyl","hp")]
predsCar1 <- estimates_DT[["beta_0"]] + car1data$cyl*estimates_DT[["beta_1"]]+car1data$hp*estimates_DT[["beta_2"]]
predsCar2 <- estimates_DT[["beta_0"]] + car2data$cyl*estimates_DT[["beta_1"]]+car2data$hp*estimates_DT[["beta_2"]]
list(
car1LowerCar2 = sum(predsCar1 < predsCar2),
car2LowerCar1 = sum(predsCar1 >= predsCar2)
)
}
Make sure the names provided as argument are valid names, e.g. are in rownames(mtcars)
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…