Julian
Julian

Reputation: 53

Intercept and slope functions in R

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.

Upvotes: 3

Views: 43864

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269694

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]]

Upvotes: 1

Michael Barrowman
Michael Barrowman

Reputation: 1191

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)

Upvotes: 7

Related Questions