is there an intercept and slope function in R like there is in excel? I know you can use the function "lm" to run a linear regression but for my purposes it would be much more practical to get the output simply as a number just like using intercept and slope in excel does.
-
4Look at the `coef` function. If you pass it your `lm` object it will return the coefficients of your fit. – LMc Mar 23 '21 at 22:02
-
Does this answer your question? [Extract regression coefficient values](https://stackoverflow.com/questions/6577058/extract-regression-coefficient-values) – LMc Mar 23 '21 at 22:06
-
`coef` is the way to do this in R. It is not so different to Excel; the SLOPE and INTERCEPT functions are doing linear regression to generate their values. It's best to learn "the R way" if you're using R and try not to compare with Excel. – neilfws Mar 23 '21 at 22:14
2 Answers
Once you've created your model, you can extract the intercept and slope values from the coefficients
matrix within the model. This can be extracted either using the coefficients()
/coef()
function (these are aliases of the same function), or by extracting the coefficients directly using $coefficient
. It's better to use the coefficients()
function as this can also be used on models other than lm
, and so it is a good habit.
x <- rnorm(100)
y <- 0.5*x + rnorm(100)
mod <- lm(y ~ x)
cf <- coef(mod)
cf
will now contain a vector with the (Intercept)
and x
(a.k.a, the slope). You can then extract these using either numbers:
Intercept <- cf[1]
Slope <- cf[2]
or by their names:
Intercept <- cf["(Intercept)"]
Slope <- cf["x"]
If you're doing multivariable, then it would be advised to use the names, as the order of the output may be unexpected (and again, this is a good habit to get into)

- 953
- 7
- 14
Assuming that the question is asking for intercept and slope functions for the linear model with one independent variable and intercept:
1) mean/cov/var If the idea of the question is to not use lm
then try these functions:
slope <- function(x, y) cov(x, y) / var(x)
intercept <- function(x, y) mean(y) - slope(x, y) * mean(x)
To test this use the built-in CO2 data:
coef(lm(uptake ~ conc, CO2))
## (Intercept) conc
## 19.50028981 0.01773059
with(CO2, intercept(conc, uptake))
## [1] 19.50029
with(CO2, slope(conc, uptake))
## [1] 0.01773059
2) lm If it is ok to use lm
then:
intercept <- function(x, y) coef(lm(y ~ x))[[1]]
slope <- function(x, y) coef(lm(y ~ x))[[2]]
3) lm.fit Another possibility is to use lm.fit
like this:
intercept <- function(x, y) coef(lm.fit(cbind(1, x), y))[[1]]
slope <- function(x, y) coef(lm.fit(cbind(1, x), y))[[2]]

- 254,981
- 17
- 203
- 341