dataclass {dataclass} | R Documentation |
Construct a dataclass in R
Description
Building a dataclass is easy! Provide names for each of the elements you want in your dataclass and an associated validator. The dataclass package comes with several built in validators, but you can define a custom validator as an anonymous function or named function to be bundled with your dataclass.
Usage
dataclass(...)
Arguments
... |
Elements to validate (i.e., dte_vec() will validate a date vector) |
Details
dataclass() will return a new function with named arguments for each of the elements you define here. If you want to use your dataclass on data frames or tibbles you must pass the dataclass to data_validator() to modify behavior.
Value
A function with the following properties:
* An argument for each element provided to dataclass() * Each argument in the returned function will validate inputs * An error occurs if new elements passed to the returned function are invalid * List is returned if new elements passed to the returned function are valid
Examples
my_dataclass <- dataclass(
min_date = dte_vec(1), # Ensures min_date is a date vector of length 1
max_date = dte_vec(1), # Ensures max_date is a date vector of length 1
run_data = df_like(), # Ensures run_date is a data object (i.e. tibble)
run_note = chr_vec(1) # Ensures run_note is a character vector of length 1
)
# This returns a validated list!
my_dataclass(
min_date = as.Date("2022-01-01"),
max_date = as.Date("2023-01-01"),
run_data = head(mtcars, 2),
run_note = "A note!"
)
# An example with anonymous functions
a_new_dataclass <-
dataclass(
start_date = dte_vec(1),
# Ensures calculation is a column in this data and is data like
results_df = function(df) "calculation" %in% colnames(df)
)
# Define a dataclass for creating data! Wrap in data_validator():
my_df_dataclass <-
dataclass(
dte_col = dte_vec(),
chr_col = chr_vec(),
# Custom column validator ensures values are positive!
new_col = function(x) all(x > 0)
) |>
data_validator()
# Validate a data frame or data frame like objects!
data.frame(
dte_col = as.Date("2022-01-01"),
chr_col = "String!",
new_col = 100
) |>
my_df_dataclass()