R中的分类变量-R选择哪一个作为参考? [英] Categorical variables in R - which one does R pick as reference?

查看:285
本文介绍了R中的分类变量-R选择哪一个作为参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当R使用分类变量执行回归时,它实际上是伪编码。也就是说,省略了一个级别作为基准或参考,并且回归公式包括了所有其他级别的虚拟变量。但是R选择哪个作为参考,以及我如何影响选择呢?

When R performs a regression using a categorical variable, it's effectively dummy coding. That is, one of levels is omitted as base or reference and the regression formula includes dummies for all the other levels. But which one is it, that R picks as reference and how I can influence this choice?

具有四个级别的示例数据(来自 UCLA的IDRE ):

Example data with four levels (from UCLA's IDRE):

hsb2 <- read.csv("http://www.ats.ucla.edu/stat/data/hsb2.csv")

summary(lm(write ~ factor(race), data = hsb2))
# level 1 is the reference level

hsb2.ordered <- hsb2[rev(order(hsb2$race)),]

summary(lm(write ~ factor(race), data = hsb2.ordered))
# level 1 is still the reference level


推荐答案

R中因子水平的顺序 not 取决于数据的顺序。因此,更改数据顺序不会影响因子的参考水平。

The order of factor levels in R does not depend on the order of the data. Hence, changing the order of the data does not affect the reference level of the factor.

您可以使用函数获得水平的顺序。级别

fac <- factor(hsb2$race)
levels(fac)
# [1] "1" "2" "3" "4"

因子级别的顺序基于数据的字母顺序。

The order of factor levels is based on the alphabetical order of the data.

您可以使用 relevel 函数:

fac2 <- relevel(fac, ref = "2")
levels(fac2)
# [1] "2" "1" "3" "4"

现在,级别 2 是参考级别。这也会影响回归:

Now, level "2" is the reference level. This also affects the regression:

lm(write ~ fac2, data = hsb2)
#
# Call:
# lm(formula = write ~ fac2, data = hsb2)
# 
# Coefficients:
# (Intercept)        fac21        fac23        fac24  
#      58.000      -11.542       -9.800       -3.945  

函数 factor 允许用于创建因子级别的任何顺序:

The function factor allows for creating any ordering of factor levels:

fac3 <- factor(fac, levels = c("3", "4", "2", "1"))
levels(fac3)
# [1] "3" "4" "2" "1"

这篇关于R中的分类变量-R选择哪一个作为参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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