How to get trendline equations in R

Jio picture Jio · Jul 22, 2014 · Viewed 26.7k times · Source

i have a series of data in form of time and temperature value. I want to generate a trendline and find the subsequent equation. This could be done in excel. but, how could i find equation of the trendline in R.

abline function can be used to generate a trendline but where is the underlying equation?? I saw a link where they have used the following code to illustrate the issue

x <- sample(1:100, 100, replace = TRUE)

y <- x + rnorm(100, sd = 4)
mydf <- data.frame(x = x, y = y)
plot(y ~ x, data = mydf)
model <- lm(y ~ x, data = mydf)
abline(model, col = "red")
summary(model)

if you execute it, can make some sense of the result and see the equation, please let me know. else help me to get equation of trendlines with R

Thanks!

Answer

Konrad Rudolph picture Konrad Rudolph · Jul 22, 2014

but where is the underlying equation?

In the “Coefficients”:

> coef(model)
(Intercept)           x
  1.2093273   0.9786051

Where “(Intercept)” is, well, the y-intercept, and “x” is the slope. In other words, you can retrieve the equation like this:

paste('y =', coef(model)[[2]], '* x', '+', coef(model)[[1]])