R lm() Function – Fitting Linear Models

R lm() function stands for linear models that is used to fit linear regression models. By using this function you can perform simple and multiple linear regression models. lm() returns an object of class lm or for multiple responses of class c("mlm","lm").

In this article, I will explain the lm() function and how to use this function with code examples.

1. Quick Examples of lm() in R

Following are quick examples of using lm() function.


# Below are quick examples of lm() function

# DataFrame with sample data
df <- data.frame( x= c(1,2,3,4,5,6,6,7,9,9),
                  y= c(1,6,10,15,20,25,22,24,26,21))

# Run linear model with formula
lmResult <- lm(y ~ x, data=df)

# Summary of linear model result
summary(lmResult)

# View plot
plot(lmResult)

# Plot abline plot
plot( df$x, df$y )
abline(lmResult)

2. Syntax of lm() Function

The following is the syntax of the lm() function.


# lm() function
lm(formula, data, subset, weights, na.action,
   method = "qr", model = TRUE, x = FALSE, y = FALSE, qr = TRUE,
   singular.ok = TRUE, contrasts = NULL, offset, …)

Parameters of lm() Function

  • formula – The formula to be applied for the linear model, it should be in the form y ~ x1 + x2
  • data – The data frame object.

3. R lm() Function with Examples

The lm() function in R is sued to create a regression model with the given formula and the data from the DataFrame, the formula should be in the form of Y~X+X2. Once the regression model is executed, use the model result to summary() function.


# DataFrame with sample data
df <- data.frame( x= c(1,2,3,4,5,6,6,7,9,9),
                  y= c(1,6,10,15,20,25,22,24,26,21))

# Run linear model with formula
lmResult <- lm(y ~ x, data=df)

# Summary of linear model result
summary(lmResult)

Yields the below output.

lm in r

Conclusion

In this article, you have learned the syntax of lm() function in R and usage with examples. The lm() function stands for linear models that is used to fit linear regression models. By using this function you can perform simple and multiple linear regression models. lm() returns an object of class lm or for multiple responses of class c("mlm","lm").

Related Articles

NNK

SparkByExamples.com is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..

Leave a Reply

You are currently viewing R lm() Function – Fitting Linear Models