Recoding
Last updated: January 18, 2021
Basic recoding
df <- df %>%
mutate(
smoke = recode(
smoke,
"1" = "Yes",
"0" = "No"
)
)This will recode 1 to Yes, and 0 to No. A few notes:
- If the original values are numeric, you still have to put them in quotes in
recode(). - You will get a warning if your recoding is not exhaustive. To suppress, add
.default = NONEtorecode().
Recoding logical values (TRUE and FALSE)
recode() currently does not work with logical values:
recode(c(T,F), T=1, F=2)
# Error in UseMethod("recode") :
# no applicable method for 'recode' applied to an object of class "logical"To make this work, do the following:
recode(as.numeric(c(T,F)), "1"=1, "0"=2)
# [1] 1 2Setup for running the example code
This example uses the birthwt dataset. If you want to run the example code, first run this:
library(MASS) # Needed for `birthwt` dataset
library(tidyverse)
df <- birthwt # Information: https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/birthwt.html
âšī¸ This page is part of my knowledge base for R, the popular statistical programming language. I attempt to use idiomatic practices with the tidyverse collection of packages as much as possible. If you have suggestions for ways to improve this code, please contact me or use the survey link below..