Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R lm() Function - Linear Regression Model

R lm() Function - Linear Regression Model

R Language Examples R Language Examples

The R lm() function is used to fit a linear regression model, analyzing the linear relationship between independent and dependent variables.

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

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

lm(formula, data)

Parameter Description:

Example

Advertising investment 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 a 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

)

)

The output of the code above is:

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, meaning advertising investment can explain about 97% of the variation in sales.

R Language Examples R Language Examples