Skip to content

Instantly share code, notes, and snippets.

@guidocor
Last active January 17, 2022 14:57
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 guidocor/10cb6ce0eee13cbeee21a6f9aa254cb3 to your computer and use it in GitHub Desktop.
Save guidocor/10cb6ce0eee13cbeee21a6f9aa254cb3 to your computer and use it in GitHub Desktop.
# Sometimes, you will find useful to discretize a variable.
# An option to do that is creating three equal sized groups
# this is, trichotomization.
# Reference http://www.stat.columbia.edu/~gelman/research/published/thirds5.pdf
library(Hmisc)
# We use cut2 to create three equal groups
# then, by taking the number with as.numeric
# we will have a column filled with the group membership
# as 1, 2 and 3.
mtcars$wt_q <- as.numeric(cut2(mtcars$wt, g = 3))
# Substracting 2 we get the group membership coded
# as -1, 0 and 1. Then, we convert it in a factor
mtcars$wt_q <- as.factor(mtcars$wt_q - 2)
# We set the central group as reference level
mtcars$wt_q = relevel(mtcars$wt_q, ref="0")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment