Skip to contents

Creates a data frame with specified column types and validation rules. Ensures that the data frame adheres to the specified structure and validation rules during creation and modification.

Usage

type.frame(
  frame,
  col_types,
  freeze_n_cols = TRUE,
  row_callback = NULL,
  allow_na = TRUE,
  on_violation = c("error", "warning", "silent")
)

Arguments

frame

The base data structure (e.g., data.frame, data.table).

col_types

A list of column types and validators.

freeze_n_cols

Logical, whether to freeze the number of columns (default: TRUE).

row_callback

A function to validate and process each row (optional).

allow_na

Logical, whether to allow NA values (default: TRUE).

on_violation

Action to take on violation: "error", "warning", or "silent" (default: "error").

Value

A function that creates typed data frames. When called, this function returns an object of class 'typed_frame' (which also inherits from the base frame class used, i.e. data.frame, data.table).

Details

The `type.frame` function defines a blueprint for a data frame, specifying the types of its columns and optional validation rules for its rows. When a data frame is created or modified using this blueprint, it ensures that all data adheres to the specified rules.

Examples

# Define a typed data frame
PersonFrame <- type.frame(
    frame = data.frame,
    col_types = list(
        id = integer,
        name = character,
        age = numeric,
        is_student = logical
    )
)

# Create a data frame
persons <- PersonFrame(
    id = 1:3,
    name = c("Alice", "Bob", "Charlie"),
    age = c(25, 30, 35),
    is_student = c(TRUE, FALSE, TRUE)
)

print(persons)
#> Typed Data Frame Summary:
#> Base Frame Type: data.frame
#> Dimensions: 3 rows x 4 columns
#> 
#> Column Specifications:
#>   id         : integer
#>   name       : character
#>   age        : numeric
#>   is_student : logical
#> 
#> Frame Properties:
#>   Freeze columns : Yes
#>   Allow NA       : Yes
#>   On violation   : error
#> 
#> Data Preview:
#>   id    name age is_student
#> 1  1   Alice  25       TRUE
#> 2  2     Bob  30      FALSE
#> 3  3 Charlie  35       TRUE

# Invalid modification (throws error)
try(persons$id <- letters[1:3])
#> Error : Property 'id' must be of type integer

# Adding a column (throws error if freeze_n_cols is TRUE)
try(persons$yeet <- letters[1:3])
#> Error in `$<-.typed_frame`(`*tmp*`, yeet, value = c("a", "b", "c")) : 
#>   Adding new columns is not allowed when freeze_n_cols is TRUE