Recoding Variables"

knitr::opts_chunk$set(collapse = TRUE, warning = FALSE, comment = "#>")
if (!requireNamespace("dplyr", quietly = TRUE)) {
  knitr::opts_chunk$set(eval = FALSE)


Data preparation is a common task in research, which usually takes the most amount of time in the analytical process. sjmisc is a package with special focus on transformation of variables that fits into the workflow and design-philosophy of the so-called "tidyverse".

Basically, this package complements the dplyr package in that sjmisc takes over data transformation tasks on variables, like recoding, dichotomizing or grouping variables, setting and replacing missing values, etc. A distinctive feature of sjmisc is the support for labelled data, which is especially useful for users who often work with data sets from other statistical software packages like SPSS or Stata.

This vignette demonstrate some of the important recoding-functions in sjmisc. The examples are based on data from the EUROFAMCARE project, a survey on the situation of family carers of older people in Europe. The sample data set efc is part of this package.


To show the results after recoding variables, the frq() function is used to print frequency tables.

Dichotomization: dividing variables into two groups

dicho() dichotomizes variables into "dummy" variables (with 0/1 coding). Dichotomization is either done by median, mean or a specific value (see argument

Like all recoding-functions in sjmisc, dicho() returns the complete data frame including the recoded variables, if the first argument is a data.frame. If the first argument is a vector, only the recoded variable is returned. See this vignette for details about the function-design.

If dicho() returns a data frame, the recoded variables have the same name as the original variable, including a suffix _d.

# age, ranged from 65 to 104, in this output
# grouped to get a shorter table
frq(efc, e17age, auto.grp = 5)

# splitting is done at the median by default:
median(efc$e17age, na.rm = TRUE)

# the recoded variable is now named "e17age_d"
efc <- dicho(efc, e17age)
frq(efc, e17age_d)

As dicho(), like all recoding-functions, supports labelled data, the variable preserves it variable label (but not the value labels). You can directly define value labels inside the function:

x <- dicho(efc$e17age, val.labels = c("young age", "old age"))

To split a variable at a different value, use the The value specified in is inclusive, i.e. all values from lowest to and including are recoded into the lower category, while all values above are recoded into the higher category.

# split at upper quartile
x <- dicho(
  efc$e17age, = quantile(efc$e17age, probs = .75, na.rm = TRUE), 
  val.labels = c("younger three quarters", "oldest quarter")

Since the distribution of values in a dataset may differ for different subgroups, all recoding-functions also work on grouped data frames. In the following example, first, the age-variable e17age is dichotomized at the median. Then, the data is grouped by gender (c161sex) and the dichotomization is done for each subgroup, i.e. it once relates to the median age in the subgroup of female, and once to the median age in the subgroup of male family carers.

x1 <- dicho(efc$e17age)

x2 <- efc %>% 
  dplyr::group_by(c161sex) %>% 
  dicho(e17age) %>% 

# median age of total sample

# median age of total sample, with median-split applied
# to distribution of age by subgroups of gender

Splitting variables into several groups

split_var() recodes numeric variables into equal sized groups, i.e. a variable is cut into a smaller number of groups at specific cut points. The amount of groups depends on the n-argument and cuts a variable into n quantiles.

Similar to dicho(), if the first argument in split_var() is a data frame, the complete data frame including the new recoded variable(s), with suffix _g, is returned.

x <- split_var(efc$e17age, n = 3)

Unlike dplyr's ntile(), split_var() never splits a value into two different categories, i.e. you always get a "clean" separation of original categories. In other words: cases that have identical values in a variable will always be recoded into the same group. The following example demonstrates the differences:

x <- dplyr::ntile(efc$neg_c_7, n = 3)
# for some cases, value "10" is recoded into category "1",
# for other cases into category "2". Same is true for value "13"
table(efc$neg_c_7, x)

x <- split_var(efc$neg_c_7, n = 3)
# no separation of cases with identical values.
table(efc$neg_c_7, x)

split_var(), unlike ntile(), does therefor not always return exactly equal-sized groups:

x <- dplyr::ntile(efc$neg_c_7, n = 3)

x <- split_var(efc$neg_c_7, n = 3)

Recode variables into equal-ranged groups

With group_var(), variables can be grouped into equal ranged categories, i.e. a variable is cut into a smaller number of groups, where each group has the same value range. group_labels() creates the related value labels.

The range of the groups is defined in the size-argument. At the same time, the size-argument also defines the lower bound of one of the groups.

For instance, if the lowest value of a variable is 1 and the maximum is 10, and size = 5, then

a) each group will have a range of 5, and b) one of the groups will start with the value 5.

This means, that an equal-ranged grouping will define groups from 0 to 4, 5 to 9 and 10-14. Each of these groups has a range of 5, and one of the groups starts with the value 5.

The group assignment becomes clearer, when group_labels() is used in parallel:

x <- round(runif(n = 150, 1, 10))


frq(group_var(x, size = 5))

group_labels(x, size = 5)

dummy <- group_var(x, size = 5, as.num = FALSE)
levels(dummy) <- group_labels(x, size = 5)

dummy <- group_var(x, size = 3, as.num = FALSE)
levels(dummy) <- group_labels(x, size = 3)

The argument right.interval can be used when size should indicate the upper bound of a group-range.

dummy <- group_var(x, size = 4, as.num = FALSE)
levels(dummy) <- group_labels(x, size = 4)

dummy <- group_var(x, size = 4, as.num = FALSE, right.interval = TRUE)
levels(dummy) <- group_labels(x, size = 4, right.interval = TRUE)

Flexible recoding of variables

rec() recodes old values of variables into new values, and can be considered as a "classical" recode-function. The recode-pattern, i.e. which new values should replace the old values, is defined in the rec-argument. This argument has a specific "syntax":

Here are some examples:


# replace NA with 5
frq(rec(efc$e42dep, rec = "NA=5;else=copy"))

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

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

# recode numeric to character, and remaining values
# into the highest value (="hi") of e42dep
frq(rec(efc$e42dep, rec = "1=first;2=2nd;else=hi"))

frq(rec(iris, Species, rec = "setosa=huhu; else=copy", append = FALSE))

# works with mutate
efc %>%
  dplyr::select(e42dep, e17age) %>%
  dplyr::mutate(dependency_rev = rec(e42dep, rec = "rev")) %>%

# recode multiple variables and set value labels via recode-syntax
dummy <- rec(
  efc, c160age, e17age,
  rec = "15:30=1 [young]; 31:55=2 [middle]; 56:max=3 [old]",
  append = FALSE

Scoped variants

Where applicable, the recoding-functions in sjmisc have "scoped" versions as well, e.g. dicho_if() or split_var_if(), where transformation will be applied only to those variables that match the logical condition of predicate.

Try the sjmisc package in your browser

Any scripts or data that you put into this service are public.

sjmisc documentation built on May 29, 2024, 10:11 a.m.