如何在回归中强制R使用指定的因子水平作为参考? [英] How to force R to use a specified factor level as reference in a regression?

查看:677
本文介绍了如何在回归中强制R使用指定的因子水平作为参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在回归中使用二进制解释变量,如何告诉R使用某个级别作为参考?

How can I tell R to use a certain level as reference if I use binary explanatory variables in a regression?

默认情况下,它仅使用某个级别.

It's just using some level by default.

lm(x ~ y + as.factor(b)) 

b {0, 1, 2, 3, 4}.假设我要使用3而不是R使用的零.

with b {0, 1, 2, 3, 4}. Let's say I want to use 3 instead of the zero that is used by R.

推荐答案

请参见relevel()函数.这是一个示例:

See the relevel() function. Here is an example:

set.seed(123)
x <- rnorm(100)
DF <- data.frame(x = x,
                 y = 4 + (1.5*x) + rnorm(100, sd = 2),
                 b = gl(5, 20))
head(DF)
str(DF)

m1 <- lm(y ~ x + b, data = DF)
summary(m1)

现在使用relevel()函数更改DF中的因子b:

Now alter the factor b in DF by use of the relevel() function:

DF <- within(DF, b <- relevel(b, ref = 3))
m2 <- lm(y ~ x + b, data = DF)
summary(m2)

模型估计了不同的参考水平.

The models have estimated different reference levels.

> coef(m1)
(Intercept)           x          b2          b3          b4          b5 
  3.2903239   1.4358520   0.6296896   0.3698343   1.0357633   0.4666219 
> coef(m2)
(Intercept)           x          b1          b2          b4          b5 
 3.66015826  1.43585196 -0.36983433  0.25985529  0.66592898  0.09678759

这篇关于如何在回归中强制R使用指定的因子水平作为参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆