从 R 中的 excel 复制多元回归图
replicate multiple regression plot from excel in R
我正在努力在 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 中实现上述目标,将不胜感激。
使用类似
的东西
matplot(seq(nrow(test)), cbind(test$y, predict(reg), rstudent(reg)), type="l")
但您必须设置轴以确保一切正常
你可以尝试这样的事情。更容易调试代码。
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_line
替换为 geom_smooth()
我正在努力在 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 中实现上述目标,将不胜感激。
使用类似
的东西matplot(seq(nrow(test)), cbind(test$y, predict(reg), rstudent(reg)), type="l")
但您必须设置轴以确保一切正常
你可以尝试这样的事情。更容易调试代码。
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_line
替换为 geom_smooth()