Skip to contents

Combines levels from two columns into new level stored into a new column. Allows users to create new classifications using levels defined in existing fields.

Usage

combine_levels(data, vars, conds, default = NA, combine = TRUE)

Arguments

data

tbl. Data frame containing the two columns to be summarized.

vars

named list of length 1. The name of the list component will be used as the name for the newly created variable/column, and the character elements specifies the two existing fields from which the levels will be combined.

conds

named list. The name of the each of the list element will be used as the label for the new level created, and the two character vectors represent the levels in the first and second variables, respectively, that will be combined to create the new level.

default

character (or NA). One of the two input variables specified in vars that will be used to set the levels of the new column after all the combinations in conds are exhausted. If default = NA, the remaining conditions conds have been exhausted will be set to NA.

combine

logical. Whether to combine the summary score column with the input data frame (Default: TRUE).

Value

tbl. The input data frame with the new column with combined levels appended at the end.

Examples

data <- tibble::tibble(
  var_1 = c("a", "b", "b", "c"),
  var_2 = c(1, NA, 2, 3)
)

data |>
  combine_levels(
    vars = list(
      "var_3" = c("var_1", "var_2")
    ),
    conds = list(
      "a1" = list("a", 1),
      "b0" = list("b", NA),
      "b2" = list("b", 2)
    ),
    default = "var_1",
    combine = TRUE
  )
#> # A tibble: 4 × 3
#>   var_1 var_2 var_3
#>   <chr> <dbl> <chr>
#> 1 a         1 a1   
#> 2 b        NA b0   
#> 3 b         2 b2   
#> 4 c         3 c