我一直在研究这个例子,我在网上发现了几个小时,无法正确计算代码以计算多个预测变量。我一直在研究R中的矩阵运算,但我在编码方面效率不高。我在excel中写出来并使其正常工作,但我无法将所有函数转换回R代码。我无法解决X2和X3。
attach(mtcars)
lm = lm(mpg~hp+disp+ qsec,mtcars)
lm
## Create X and Y matrices for this specific regression
X = as.matrix(cbind(1,mtcars$hp))
X2 = as.matrix(cbind(1,mtcars$disp))
X3 = as.matrix(cbind(1,mtcars$qsec))
Y = as.matrix(mtcars$mpg)
## Choose beta-hat to minimize the sum of squared residuals
## resulting in matrix of estimated coefficients:
bh = round(solve(t(X)%*%X)%*%t(X)%*%Y, digits=4)
## Label and organize results into a data frame
beta.hat = as.data.frame(cbind(c("Intercept","Height"),bh))
names(beta.hat) = c("Coeff.","Est")
beta.hat
答案 0 :(得分:1)
你可能正在寻找这个:
## Create X and Y matrices for this specific regression
X <- with(mtcars, as.matrix(cbind(1,hp,disp,qsec)))
Y <- as.matrix(mtcars$mpg)
bh <- round(solve(t(X)%*%X)%*%t(X)%*%Y, digits=5)
rownames(bh)[1] <- "Intercept"
bh
# [,1]
# Intercept 38.62221
# hp -0.03464
# disp -0.02847
# qsec -0.38556
lm
# Call:
# lm(formula = mpg ~ hp + disp + qsec, data = mtcars)
# Coefficients:
# (Intercept) hp disp qsec
# 38.62221 -0.03464 -0.02847 -0.38556