recode_to_binary {tntpr} | R Documentation |
Recode a variable into binary groups, e.g., "Top-2" and "Not in Top-2".
Description
Recodes a character variable into a binary result, a two-level factor. All values matching of the supplied character strings in the to_match
vector are coded into the first level of the factor; all other values are coded into the other level. NA
remains NA
. The default factor labels are "Selected" and "Not selected" but these can be overridden.
This recoding is not case-sensitive; if you specify "agree" as a top-2 value, "Agree" will be counted as Top-2, and vice versa.
Usage
recode_to_binary(
x,
to_match = c("strongly agree", "agree"),
label_matched = "Selected",
label_unmatched = "Not selected"
)
Arguments
x |
the character or factor vector to be recoded |
to_match |
a character vector with the strings that should be put in the first level of the factor. Defaults to "strongly agree" and "agree" but can be overwritten. |
label_matched |
what should be the factor label of values that match the strings specified in |
label_unmatched |
what should be the factor label of values that don't match the strings specified in |
Value
a factor variable (for nicer ordering in calls to janitor::tabyl
) with values mapped to the two levels.
Examples
agreement <- c(
"Strongly agree", "Agree", "Somewhat agree",
"Somewhat disagree", "Strongly disagree", "Frogs", NA
)
recode_to_binary(agreement) # default values of "strongly agree" and "agree" are used for recoding
recode_to_binary(agreement,
label_matched = "Top-2 Agree",
label_unmatched = "Not in Top-2"
) # custom labels of factor levels
recode_to_binary(agreement, "frogs")
recode_to_binary(
agreement,
"frogs",
"FROGS!!!",
"not frogs"
) # custom matching values & labels of factor levels
freq <- c("always", "often", "sometimes", "never")
recode_to_binary(freq, "always", "always", "less than always")