Learn R Programming

sjmisc (version 1.0.2)

rec: Recode numeric variables

Description

Recodes the categories of a (numeric) variable x into new category values.

Usage

rec(x, recodes)

Arguments

x
a numeric variable (vector) or a factor with numeric levels that should be recoded; or a data frame with such vectors.
recodes
a string with recode pairs of old and new values. See details for examples.

Value

  • A numeric variable with recoded category values, or a data frame with recoded categories for all variables.

Details

The recodes string has following syntax:
  • each recode pair has to be separated by a;, e.g.recodes = "1=1; 2=4; 3=2; 4=3"
  • multiple old values that should be recoded into a new single value may be separated with comma, e.g."1,2=1; 3,4=2"
  • a value range is indicated by a colon, e.g."1:4=1; 5:8=2"(recodes all values from 1 to 4 into 1, and from 5 to 8 into 2)
  • minimum and maximum values are indicates byminandmax, e.g."min:4=1; 5:max=2"(recodes all values from minimum values ofxto 4 into 1, and from 5 to maximum values ofxinto 2)
  • all other values except specified are indicated byelse, e.g."3=1; 1=2; else=3"(recodes 3 into 1, 1 into 2 and all other values into 3)
  • NAvalues are allowed both as old and new value, e.g."NA=1; 3:5=NA"(recodes all NA from old value into 1, and all old values from 3 to 5 into NA in the new variable)
  • "rev"is a special token that reverses the value order (see examples)

See Also

set_na for setting NA values and recode_to for re-shifting value ranges.

Examples

Run this code
data(efc)
table(efc$e42dep, exclude = NULL)

# replace NA with 5
table(rec(efc$e42dep, "1=1;2=2;3=3;4=4;NA=5"), exclude = NULL)

# recode 1 to 2 into 1 and 3 to 4 into 2
table(rec(efc$e42dep, "1,2=1; 3,4=2"), exclude = NULL)

# recode 1 to 3 into 4 into 2
table(rec(efc$e42dep, "min:3=1; 4=2"), exclude = NULL)

# recode 2 to 1 and all others into 2
table(rec(efc$e42dep, "2=1; else=2"), exclude = NULL)

# reverse value order
table(rec(efc$e42dep, "rev"), exclude = NULL)

# recode variables with same categorie in a data frame
head(efc[, 6:9])
head(rec(efc[, 6:9], "1=10;2=20;3=30;4=40"))

Run the code above in your browser using DataLab