Skip to contents

Classifies a variable as continuous, binary, ordinal, count, or categorical from its R class and the number of distinct non-missing values. The rest of the package leans on this to pick correlation methods, but it is exported because the classification is useful on its own.

Usage

detect_type(x, ordinal_threshold = 10, detect_count = TRUE, verbose = FALSE)

Arguments

x

A vector (numeric, factor, character, or logical).

ordinal_threshold

Integer. Numeric variables with this many or fewer unique non-missing values are classified as ordinal. Default: 10.

detect_count

Logical. If TRUE (default), numeric variables that are non-negative integer-valued and exceed ordinal_threshold distinct values are classified as "count". Set to FALSE to treat all such variables as "continuous".

verbose

Logical. If TRUE, prints the detection reasoning. Default: FALSE.

Value

A single character string: "continuous", "binary", "ordinal", "count", or "categorical".

Details

The detection follows these rules, in order:

  1. Ordered factors are always classified as "ordinal".

  2. Unordered factors and character vectors are classified as "categorical", except when they have exactly 2 unique values, in which case they are "binary".

  3. Logical vectors are classified as "binary".

  4. Numeric vectors with exactly 2 unique values are "binary".

  5. Numeric vectors with unique values at or below ordinal_threshold are "ordinal".

  6. Numeric vectors that are non-negative integers with more than ordinal_threshold unique values are classified as "count". Disable by setting detect_count = FALSE.

  7. All other numeric vectors are "continuous".

The ordinal_threshold parameter controls the heuristic for numeric variables: if a numeric variable has at most this many distinct values, it is assumed to represent ordered categories (e.g., a 1–5 Likert scale stored as integers). Set to 0 to disable this heuristic and treat all numeric variables as continuous (or count, if non-negative integer-valued).

Examples

path = system.file("extdata", "gss_2024_casestudy.csv", package = "smartcor")
gss = read.csv(path)
vapply(gss, detect_type, character(1))
#>           age        coninc        degree         happy           sex 
#>       "count"  "continuous"     "ordinal"     "ordinal"      "binary" 
#>       marital        region 
#>      "binary" "categorical"