Last active
January 17, 2022 14:57
-
-
Save guidocor/10cb6ce0eee13cbeee21a6f9aa254cb3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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