R lm() Function - Linear Regression Model

R 语言实例R Language Examples

The R lm() function is used to fit linear regression models and analyze the linear relationship between independent and dependent variables.

Linear regression is one of the most fundamental and important tools in statistical modeling.

The syntax of the lm() function is as follows:

lm(formula, data)

Parameter description:

  • formulaFormula, in the format y ~ x1 + x2 + ..., where y is the dependent variable and x are the independent variables.

  • dataData frame, containing the variables in the formula.

Example

# Advertising spend and sales data
ad_spend <- c(10, 15, 12, 18, 20, 14, 22, 16, 25, 19)
sales <- c(50, 65, 55, 72, 80, 60, 88, 68, 95, 75)

# Fit the linear model
model <- lm(sales ~ ad_spend)

# View the model summary
print(summary(model))

# Predict new data
new_spend <- data.frame(ad_spend = c(17, 23))
predictions <- predict(model, new_spend)
print(paste("Predicted sales:", predictions))

Executing the above code produces the following output:

Call:
lm(formula = sales ~ ad_spend)

Residuals:
    Min      1Q  Median      3Q     Max
-4.3780 -1.5831 -0.4329  1.8202  4.9347

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  17.1622     3.4394   4.990  0.00106 **
ad_spend      3.0623     0.1933  15.839  2.42e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.829 on 8 degrees of freedom
Multiple R-squared:  0.9691,    Adjusted R-squared:  0.9652
F-statistic: 250.9 on 1 and 8 DF,  p-value: 2.422e-07

[1] "预测销售额: 69.2218150385764 87.5953501640316"

R-squared is 0.9691, indicating that advertising spend can explain about 97% of the variation in sales.

R 语言实例R Language Examples

Other extensions