# R语言 多重回归

2022-06-16 15:57 更新

```y = a + b1x1 + b2x2 +...bnxn
```

• y是响应变量。

• a，b1，b2 ... bn是系数。

• x1，x2，... xn是预测变量。

## lm()函数

### 语法

lm()函数在多元回归中的基本语法是 -

```lm(y ~ x1+x2+x3...,data)
```

• 公式是表示响应变量和预测变量之间的关系的符号。

• 数据是应用公式的向量。

## 例

### 输入数据

```input <- mtcars[,c("mpg","disp","hp","wt")]
```

```                   mpg   disp   hp    wt
Mazda RX4          21.0  160    110   2.620
Mazda RX4 Wag      21.0  160    110   2.875
Datsun 710         22.8  108     93   2.320
Hornet 4 Drive     21.4  258    110   3.215
Hornet Sportabout  18.7  360    175   3.440
Valiant            18.1  225    105   3.460
```

### 创建关系模型并获取系数

```input <- mtcars[,c("mpg","disp","hp","wt")]

# Create the relationship model.
model <- lm(mpg~disp+hp+wt, data = input)

# Show the model.
print(model)

# Get the Intercept and coefficients as vector elements.
cat("# # # # The Coefficient Values # # # ","
")

a <- coef(model)[1]
print(a)

Xdisp <- coef(model)[2]
Xhp <- coef(model)[3]
Xwt <- coef(model)[4]

print(Xdisp)
print(Xhp)
print(Xwt)
```

```Call:
lm(formula = mpg ~ disp + hp + wt, data = input)

Coefficients:
(Intercept)         disp           hp           wt
37.105505      -0.000937        -0.031157    -3.800891

# # # # The Coefficient Values # # #
(Intercept)
37.10551
disp
-0.0009370091
hp
-0.03115655
wt
-3.800891
```

### 创建回归模型的方程

```Y = a+Xdisp.x1+Xhp.x2+Xwt.x3
or
Y = 37.15+(-0.000937)*x1+(-0.0311)*x2+(-3.8008)*x3
```

### 应用方程预测新值

```Y = 37.15+(-0.000937)*221+(-0.0311)*102+(-3.8008)*2.91 = 22.7104
```

App下载