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
爲什麼你定義X2和X3?你不使用它們。 – 2015-02-12 05:04:34