0
$\begingroup$

Consider the following reproducible example:

library(dplyr)
library(psych)

set.seed(42)
n <- 500

df <- data.frame(
  loneliness = round(runif(n, 0, 1)),
  pet = factor(round(runif(n, 0, 1))),
  addiction = factor(round(runif(n, 0, 2))),
  sex = factor(round(runif(n, 0, 1)))
)

levels(df$pet) <- c('dog', 'cat')
levels(df$addiction) <- c('none', 'low', 'high')
levels(df$sex) <- c('male', 'female')

df_coded <- data.frame(
  loneliness = df$loneliness,
  psych::dummy.code(df$pet) %>% as_tibble() %>%  setNames(paste0('pet_', names(.))),
  psych::dummy.code(df$addiction) %>% as_tibble() %>%  setNames(paste0('addiction_', names(.))),
  psych::dummy.code(df$sex) %>% as_tibble() %>%  setNames(paste0('sex_', names(.)))
)


model_formula <- as.formula(
  paste0(
    'loneliness ~ 0 +',
      paste0(colnames(df_coded)[-1], collapse = ' + ')
  )
)

print(glm(formula = model_formula, data = df_coded, family = binomial))

I want to level mean code my variables since I am not interested in an intercept and don't want it to results in the intersections between the first levels of pet, addiction and sex. Hence, I want to evaluate each level of each of these three predictors separately. As you can see by my attempt above, fixing the intercept to 0 while keeping all predictors with each level in the model, works fine for the first variable (pet), but produces NA's for the last level of the subsequent variables (addiction and sex):

> source('~/.active-rstudio-document')

Call:  glm(formula = model_formula, data = df_coded, family = binomial)

Coefficients:
       pet_dog         pet_cat   addiction_low  addiction_none  addiction_high      sex_female        sex_male  
       0.49977         0.45998         0.02604        -0.02391              NA        -0.03488              NA 

What is the reason behind this and how do I prevent it? Thanks

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.