在R中从excel复制多元回归图
我正在努力在R中复制一个多元线性回归图,这在Excel中很容易获得。 我举个例子。假设我在R中有以下数据帧(称为test): 要生成线性回归,我只需写下:在R中从excel复制多元回归图,r,linear-regression,timeserieschart,R,Linear Regression,Timeserieschart,我正在努力在R中复制一个多元线性回归图,这在Excel中很容易获得。 我举个例子。假设我在R中有以下数据帧(称为test): 要生成线性回归,我只需写下: reg=lm(y ~ x1 + x2 + x3, data = test) 现在,我想创建一个y变量的实际值,预测的y和次轴上的标准化残差的曲线图。我从Excel中添加了一个屏幕截图,让您明白我的意思 要访问我想要获得的Excel绘图,请执行以下操作: 如果有人能告诉我谁能在R中实现上述目标,我将不胜感激。请使用 matplot(seq(
reg=lm(y ~ x1 + x2 + x3, data = test)
现在,我想创建一个y变量的实际值,预测的y和次轴上的标准化残差的曲线图。我从Excel中添加了一个屏幕截图,让您明白我的意思
要访问我想要获得的Excel绘图,请执行以下操作:
如果有人能告诉我谁能在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()
测试非常感谢!太好了,我会找出秒轴的!
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()