2017-01-02 77 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()