coerce_safe {na.tools}R Documentation

coerce_safe

Description

Coerce values in a safe, non-destructive and consistent way.

Usage

coerce_safe(object, class, alert = stop, ..., alert_irreversible = alert,
  alert_na = alert)

Arguments

object

to be coerced

class

character; class to which object should be coerced.

alert

function to use to raise exceptions: (Default: base::stop())

...

unused

alert_irreversible

function to raise alert when coercion is not reversible. See Details.

alert_na

function to raise when NAs are produced.

coerce_safe transform the object to class in a safe, consistent, non-destructive way.

Safe means that coercison:

  1. is non-destructive (i.e information is not lost in the transformation )

  2. is reversible:

    f^{-1}( f(x) ) == x

  3. does not introduce (additional) missing values (NA)

By default, corece_safe raises an alert (message|warning|error) when the attempted coercion violates these constraints. The alert argument (and alert_irreversible or alert_na) can be used to fleixble change the response. Valid values for these are base::message(), base::warning() and base::stop among others.

Value

object coerced to class but ensured that there has been no loss in data and no additional Missonve values introduced.

Note

There must be a as method to the reverse coercion for this function to work.

See Also

methods::as 'coercion::try_as()“

Examples


## Not run: 
  # Error
  coerce_safe(1.01, "integer")  # 1.01 != 1
  coerce_safe( c("1","2","a"), "integer" )

## End(Not run)


[Package na.tools version 0.3.1 Index]