代码之家  ›  专栏  ›  技术社区  ›  Dr. Fabian Habersack

将国家固定效果引入glm()并设置“reference country”

glm r
  •  0
  • Dr. Fabian Habersack  · 技术社区  · 7 年前

    我需要将固定效果(在本例中是:乡村假人)引入到一个简单的场景中 glm()

    country   country_a   country_b   country_c   y   x   ...
    1         1           0           0
    1         1           0           0
    2         0           1           1
    2         0           1           1
    

    这是正确的方法吗 实施它?见下文。。。 glm(y ~ x + country_a + country_b + country_c, family=binomial(link="logit"))

    country_a 如果我决定放弃它,它仍然是我的参考类别吗?

    或者我必须用 Country glm() 不知何故,这是一个没有秩序的因素?如果是,我该怎么做?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Spacedman    7 年前

    数据如下:

    > d
      country         y         x
    1       1 0.9610213 0.2586365
    2       1 0.8561303 0.5972043
    3       2 0.5463802 0.6412527
    4       2 0.4703876 0.1126319
    

    您可以在glm调用中转换为因子:

    > glm(y~factor(country),data=d)
    
    Call:  glm(formula = y ~ factor(country), data = d)
    
    Coefficients:
         (Intercept)  factor(country)2  
              0.9086           -0.4002  
    
    Degrees of Freedom: 3 Total (i.e. Null);  2 Residual
    Null Deviance:      0.1685 
    Residual Deviance: 0.008388     AIC: -7.317
    

    > d$CountryCode = paste0("Country",d$country)
    > d
      country         y         x CountryCode
    1       1 0.9610213 0.2586365    Country1
    2       1 0.8561303 0.5972043    Country1
    3       2 0.5463802 0.6412527    Country2
    4       2 0.4703876 0.1126319    Country2
    > glm(y~CountryCode,data=d)
    
    Call:  glm(formula = y ~ CountryCode, data = d)
    
    Coefficients:
            (Intercept)  CountryCodeCountry2  
                 0.9086              -0.4002  
    
    Degrees of Freedom: 3 Total (i.e. Null);  2 Residual
    Null Deviance:      0.1685 
    Residual Deviance: 0.008388     AIC: -7.317
    

    系数表中缺失的因子水平是基线水平-在这种情况下 Country1 .

        2
  •  1
  •   Ben Bolker    7 年前

    由于R的默认(处理)分类变量对比使用第一个因子水平作为基线/截距,因此选择基线水平的最简单方法是使用 relevel()

    glm(y~relevel(factor(country),"7"), data=d)
    

    d$CountryCode = relevel(factor(paste0("Country",d$country)), "Country7")