Learn R Programming

sjmisc (version 1.0.3)

rec: Recode numeric variables

Description

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

Usage

rec(x, recodes, asFac = FALSE, varLabel = NULL, valLabels = NULL)

Arguments

x
a numeric variable (vector) or a factor with numeric levels that should be recoded; or a data.frame or list of variables.
recodes
a string with recode pairs of old and new values. See 'Details' for examples.
asFac
logical, if TRUE, recoded variable is returned as factor. Default is FALSE, thus a numeric variable is returned.
varLabel
optional string, to set variable label attribute for the recoded variable (see set_var_labels). If NULL (default), variable label attribute of x will be used (if present).
valLabels
optional character vector, to set value label attributes of recoded variable (see set_val_labels). If NULL (default), no value labels will be set.

Value

  • A numeric variable (or a factor, if asFac = TRUE) with recoded category values, or a data frame or list-object with recoded categories for all variables.

Details

The recodes string has following syntax: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

See Also

set_na for setting NA values, replace_na to replace NA's with specific value 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)

# keep value labels. variable label is automatically retained
str(rec(efc$e42dep,
        "1,2=1; 3,4=2",
        valLabels = c("low dependency", "high dependency")))

# 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 only selected values, copy remaining
table(efc$e15relat)
table(rec(efc$e15relat, "1,2,4=1; else=copy"))

# 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"))

# recode list of variables. create dummy-list of
# variables with same value-range
dummy <- list(efc$c82cop1, efc$c83cop2, efc$c84cop3)
# show original distribution
lapply(dummy, table, exclude = NULL)
# show recodes
lapply(rec(dummy, "1,2=1; NA=9; else=copy"), table, exclude = NULL)

Run the code above in your browser using DataLab