Skip to contents

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 to_match? Defaults to "Selected"

label_unmatched

what should be the factor label of values that don't match the strings specified in to_match? Defaults to "Not selected".

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
#> [1] Selected     Selected     Not selected Not selected Not selected
#> [6] Not selected <NA>        
#> Levels: Selected Not selected
recode_to_binary(agreement,
  label_matched = "Top-2 Agree",
  label_unmatched = "Not in Top-2"
) # custom labels of factor levels
#> [1] Top-2 Agree  Top-2 Agree  Not in Top-2 Not in Top-2 Not in Top-2
#> [6] Not in Top-2 <NA>        
#> Levels: Top-2 Agree Not in Top-2
recode_to_binary(agreement, "frogs")
#> [1] Not selected Not selected Not selected Not selected Not selected
#> [6] Selected     <NA>        
#> Levels: Selected Not selected
recode_to_binary(
  agreement,
  "frogs",
  "FROGS!!!",
  "not frogs"
) # custom matching values & labels of factor levels
#> [1] not frogs not frogs not frogs not frogs not frogs FROGS!!!  <NA>     
#> Levels: FROGS!!! not frogs

freq <- c("always", "often", "sometimes", "never")
recode_to_binary(freq, "always", "always", "less than always")
#> [1] always           less than always less than always less than always
#> Levels: always less than always