knitr::opts_chunk$set(collapse = TRUE, warning = FALSE, comment = "#>") suppressPackageStartupMessages(library(sjmisc))
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.
library(sjmisc) data(efc)
To show the results after recoding variables, the frq()
function is used to print frequency tables.
dicho()
dichotomizes variables into "dummy" variables (with 0/1 coding). Dichotomization is either done by median, mean or a specific value (see argument dich.by
).
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")) frq(x)
To split a variable at a different value, use the dich.by
-argment. The value specified in dich.by
is inclusive, i.e. all values from lowest to and including dich.by
are recoded into the lower category, while all values above dich.by
are recoded into the higher category.
# split at upper quartile x <- dicho( efc$e17age, dich.by = quantile(efc$e17age, probs = .75, na.rm = TRUE), val.labels = c("younger three quarters", "oldest quarter") ) frq(x)
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.
data(efc) x1 <- dicho(efc$e17age) x2 <- efc %>% dplyr::group_by(c161sex) %>% dicho(e17age) %>% dplyr::pull(e17age_d) # median age of total sample frq(x1) # median age of total sample, with median-split applied # to distibution of age by subgroups of gender frq(x2)
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) frq(x)
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) frq(x) x <- split_var(efc$neg_c_7, n = 3) frq(x)
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:
set.seed(123) x <- round(runif(n = 150, 1, 10)) frq(x) 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) frq(dummy) dummy <- group_var(x, size = 3, as.num = FALSE) levels(dummy) <- group_labels(x, size = 3) frq(dummy)
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) frq(dummy) dummy <- group_var(x, size = 4, as.num = FALSE, right.interval = TRUE) levels(dummy) <- group_labels(x, size = 4, right.interval = TRUE) frq(dummy)
rec()
recodes old values of variables into new values, and can be considered as a "classsical" 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":
recode pairs: Each recode pair has to be separated by a ;, e.g. rec = "1=1; 2=4; 3=2; 4=3"
multiple values: Multiple old values that should be recoded into a new single value may be separated with comma, e.g. rec = "1,2=1; 3,4=2"
value range: A value range is indicated by a colon, e.g. rec = "1:4=1; 5:8=2"
(recodes all values from 1 to 4 into 1, and from 5 to 8 into 2)
value range for doubles: For double vectors (with fractional part), all values within the specified range are recoded; e.g. rec = "1:2.5=1;2.6:3=2"
recodes 1 to 2.5 into 1 and 2.6 to 3 into 2, but 2.55 would not be recoded (since it's not included in any of the specified ranges)
"min" and "max": Minimum and maximum values are indicates by min
(or lo
) and max
(or hi
), e.g. rec = "min:4=1; 5:max=2"
(recodes all values from minimum values of x to 4 into 1, and from 5 to maximum values of x into 2) You can also use min
or max
to recode a value into the minimum or maximum value of a variable, e.g. rec = "min:4=1; 5:7=max"
(recodes all values from minimum values of x to 4 into 1, and from 5 to 7 into the maximum value of x).
"else": All other values, which have not been specified yet, are indicated by else, e.g. rec = "3=1; 1=2; else=3"
(recodes 3 into 1, 1 into 2 and all other values into 3)
"copy": The "else"
-token can be combined with "copy"
, indicating that all remaining, not yet recoded values should stay the same (are copied from the original value), e.g. rec = "3=1; 1=2; else=copy"
(recodes 3 into 1, 1 into 2 and all other values like 2, 4 or 5 etc. will not be recoded, but copied.
NA's: NA
values are allowed both as old and new value, e.g. rec = "NA=1; 3:5=NA"
(recodes all NA
into 1, and all values from 3 to 5 into NA in the new variable)
"rev": "rev"
is a special token that reverses the value order.
direct value labelling: Value labels for new values can be assigned inside the recode pattern by writing the value label in square brackets after defining the new value in a recode pair, e.g. rec = "15:30=1 [young aged]; 31:55=2 [middle aged]; 56:max=3 [old aged]"
non-captured values: Non-matching values will be set to NA
, unless captured by the "else"
- or "copy"
-token.
Here are some examples:
frq(efc$e42dep) # 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")) data(iris) 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")) %>% head() # 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 ) frq(dummy)
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
.
A cheatsheet can be downloaded from the RStudio cheatsheet collection.
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.