10 recode()

The recode() function replaces an initial set of values with a new set of values for a vector. The function recode_all() applies recode() to all columns in a dataset.

The inputs for recode() are the following:

  1. a vector;
  2. a set of values to replace (“initial values”); and
  3. a set of values values that will replace the initial values.
mtcars$am
##  [1] 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1
recode(mtcars$am, 0:1, 2:3)
##  [1] 3 3 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 2 2 2 2 2 3 3 3 3 3 3 3

10.2 switchv()

The switchv() function behaves the same as switch() except that it applies over a vector (i.e., it is a vectorized version of the latter). The function swap is a shorthand synonym for switchv(). The function switchv_all()/swap_all() applies switchv()/swap() to all columns in a data frame.

These functions are inspired by SPSS’s RECODE command.6

switchv(iris$Species, setosa = 4, versicolor = 5, virginica = 6)
##   [1] 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
##  [38] 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
##  [75] 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6
## [112] 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
## [149] 6 6