2017-01-02 79 views
1

我很努力在R中重現多元線性迴歸圖,這在Excel中很容易獲得。 我舉個例子。說我有R中的以下的數據幀(稱爲測試):從Excel中複製多元迴歸圖R

y x1 x2 x3 
2 5 5 9 
6 4 2 9 
4 2 6 15 
7 5 10 6 
7 5 10 6 
5 4 3 12 

要生成的線性迴歸,我簡單地寫:

reg=lm(y ~ x1 + x2 + x3, data = test) 

現在我想創建實際的值的曲線圖y變量,預測的y和第二軸上的標準化殘差。我從Excel中添加屏幕截圖,以瞭解我的意思。

來訪問Excel情節,我想獲得: the plot is in italian, "y" means observed y values, "Y prevista" means predicted Y values and "Residui standard" means standardized residuals. The standard residuals are plotted on a secondary axis

如果有人能告訴我是誰,我可以實現在R中的上方,這將是非常讚賞。

回答

1

使用類似

matplot(seq(nrow(test)), cbind(test$y, predict(reg), rstudent(reg)), type="l") 

但你必須設置軸,以確保一切正常

+0

非常感謝取代geom_line!這很好,會找出第二軸! –

0

你可以嘗試這樣的事情。更容易調試您的代碼。

test <- data.frame(y=c(2,6,4,7,7,5), x1=c(5,4,2,5,5,4), x2=c(5,2,6,10,10,3), 
        x3=c(9,9,15,6,6,12)) 

reg=lm(y ~ x1 + x2 + x3, data = test) 

# Add new columns to dataframe from regression 
test$yhat <- reg$fitted.values 
test$resid <- reg$residuals 
# Create your x-variable column 
test$X <-seq(nrow(test)) 

library(ggplot2) 
library(reshape2) 
# Columns to keep 
keep = c("y", "yhat", "resid", "X") 

# Drop columns not needed 
test <-test[ , keep, drop=FALSE] 

# Reshape for easy plotting 
test <- melt(test, id.vars="X") 

# Everything on the same plot 
ggplot(test, aes(X,value, col=variable)) + 
    geom_point() + 
    geom_line() 

對於不同的樣子,你也可以用geom_smooth()