[英]How can I compute the formula of simple linear regression in R?
I have this data:我有这个数据:
x <- c(1,3,5,8,9,0)
y <- c(5,8,9,7,4,3)
xy <- data.frame(X = x, Y = y)
I draw the simple linear regression line with this code:我用这段代码绘制了简单的线性回归线:
library(ggplot2)
MyRegression <- ggplot(xy, aes(x = x, y = y))
MyRegression + geom_point() + geom_smooth(method='lm')
Also I want to have automatically the type of the equation y=a+bx .我也想自动拥有方程式y=a+bx的类型。 I know how to compute a and b (by using this formula ), but I 'm wondering if I can do it automatically by using a simple command.
我知道如何计算a和b (通过使用这个公式),但我想知道我是否可以使用一个简单的命令自动完成。
Thanks in advance!提前致谢!
To calculate a linear model, use the R-fucntion lm
.要计算线性 model,请使用 R 函数
lm
。
mod <- lm(Y~X,data=xy)
Now you want to calculate the fitted line.现在您要计算拟合线。 This is possible via
这可以通过
lineData <- data.frame(x=xy$X,y=mod$coefficients[1]+mod$coefficients[2]*xy$X)
You can add the line by using geom_line
:您可以使用
geom_line
添加该行:
ggplot(xy, aes(x = x, y = y)) + geom_point() + geom_line(data=lineData,mapping = aes(x=x,y=y),col="red",size=2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.