Skip to content

Instantly share code, notes, and snippets.

@chrishanretty
Created May 28, 2019 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrishanretty/59f833170a4034506b4019f3c87380a1 to your computer and use it in GitHub Desktop.
Save chrishanretty/59f833170a4034506b4019f3c87380a1 to your computer and use it in GitHub Desktop.
Example of models with continuous and categorical coding
## Load packages
library(rio)
library(tidyverse)
library(gtsummary) ## optional
### Read the data
dat <- rio::import("Irine_Data.sav")
summary(dat$Retrospective_)
summary(dat$Party)
dat$Retrospective_cont <- dat$Retrospective_
## Estimate a model with retrospective as a continuous variable
mod_a <- glm(Party ~ Retrospective_cont + Higher_Education + Gender,
data = dat,
family = binomial(link = logit))
## Estimate a model with retrospective as a categorical variable
## where "Same" is the baseline
#
## First, recode
dat$Retrospective_cat <- dplyr::recode(dat$Retrospective_,
`-1` = "Worse",
`0` = "Same",
`1` = "Better")
dat$Retrospective_cat <- factor(dat$Retrospective_cat)
### Set 'same' to be the reference category
dat$Retrospective_cat <- relevel(dat$Retrospective_cat,
"Same")
## Now estimate a model
mod_b <- glm(Party ~ Retrospective_cat + Higher_Education + Gender,
data = dat,
family = binomial(link = logit))
## Optionally, display the results in a pretty table
cm <- c('(Intercept)' = '(Intercept)',
'Retrospective_cont' = 'Econ evals (retrospective; continuous)',
'Retrospective_catBetter' = 'Retrospective econ evals: better (compared to same)',
'Retrospective_catWorse' = 'Retrospective econ evals: worse (compared to same)',
'Higher_Education' = 'College graduate',
'Gender' = 'Female voter')
gtsummary(list(mod_a, mod_b), coef_map = cm,
filename = "table.html")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment