Recoding

Last updated: August 19, 2020

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:

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 2


Setup 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..