Skip to contents

Converts character columns to numeric and numeric columns to character where the var_spec data_type requires it. Factor columns are always coerced to the appropriate base type. Preserves all non-class attributes (labels, formats) across coercion. Warns when coercion introduces NA values.

Usage

coerce_types(x, spec, dataset)

Arguments

x

A data frame.

spec

A herald_spec object or a path to a spec file.

dataset

Character. The dataset name.

Value

The data frame with coerced column types (invisibly).

Examples

spec <- herald_spec(
  ds_spec = data.frame(dataset = "DM", label = "Demographics",
                       stringsAsFactors = FALSE),
  var_spec = data.frame(
    dataset   = "DM",
    variable  = c("STUDYID", "AGE"),
    data_type = c("text", "integer"),
    stringsAsFactors = FALSE
  )
)
dm <- data.frame(STUDYID = "S1", AGE = "65", stringsAsFactors = FALSE)
result <- coerce_types(dm, spec, "DM")
#> Coerced 1 variable: AGE (char→num)
is.numeric(result$AGE)    # TRUE
#> [1] TRUE
is.character(result$STUDYID)  # TRUE
#> [1] TRUE