我有一个包含多个虚拟变量的回归分析,我想在图中绘制回归线。虚拟变量是中国演员、中国合拍公司和在中国的拍摄地点。如何将其绘制在图中?
control.test <-lm(CBO.split~ Chinese.actors + Chinese.co...production.company..yes.1.no.0. + Filming.location.China..yes.1.no.0.)
summary(control.test)
答案 0 :(得分:0)
以下是使用 R 附带的 iris
数据集的示例:
data(iris)
str(iris)
# 'data.frame': 150 obs. of 5 variables:
# $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
# $ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
# $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
# $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
# $ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
levels(iris$Species)
# [1] "setosa" "versicolor" "virginica"
现在是一个使用 Species
作为虚拟变量的回归模型。
iris.lm <- lm(Sepal.Length~Sepal.Width+Species, iris)
iris.coef <- coef(iris.lm)
iris.coef
# (Intercept) Sepal.Width Speciesversicolor Speciesvirginica
# 2.2513932 0.8035609 1.4587431 1.9468166
Intercept
是 Sepal.Length
的值,当 Sepal.Width
对物种 setosa
等于 0 时,Intercept
+ Speciesversicolor
是 versicolor
的截距{1}} 和 Intercept
+ Speciesvirginica
是 virginica
的截距。所有三条线的斜率都相同。最后我们绘制结果:
plot(Sepal.Length~Sepal.Width, iris, pch=16, col=as.numeric(Species)+1)
abline(a=iris.coef[1], b=iris.coef[2], col=2)
abline(a=iris.coef[1] + iris.coef[3], b=iris.coef[2], col=3)
abline(a=iris.coef[1] + iris.coef[4], b=iris.coef[2], col=4)
legend("bottomright", levels(iris$Species), pch=16, lwd=1, col=2:4)
你的情况稍微复杂一些,因为你有两个二分变量,但它们只影响截距,斜率不会改变。