2015-02-12 114 views
0

我一直在工作这个例子,我在网上发现了几个小时,无法得到正确的代码来计算多个预测变量。我一直在研究R中的矩阵运算,但我在编码方面效率不高。我用excel写出来,让它正常工作,但我无法将所有函数都转换回R代码。我无法解决X2和X3。R矩阵回归

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

为什么你定义X2和X3?你不使用它们。 – 2015-02-12 05:04:34

回答

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