type.frame: Create a typed data frame

View source: R/type.frame.R

type.frameR Documentation

Create a typed data frame

Description

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").

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.

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).

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)

# Invalid modification (throws error)
try(persons$id <- letters[1:3])

# Adding a column (throws error if freeze_n_cols is TRUE)
try(persons$yeet <- letters[1:3])

interface documentation built on Sept. 11, 2024, 8:59 p.m.