# Create a custom positive number
Positive <- create_type("positive", function(x) {
is.numeric(x) && all(x > 0)
})
# Use it in type annotations
age %:% Positive %<-% 25
try(age <- -5) # Error: Type error
# Create a custom email type
Email <- create_type("email", function(x) {
is.character(x) &&
length(x) == 1 &&
grepl("^[^@]+@[^@]+\\.[^@]+$", x)
})
user_email %:% Email %<-% "user@example.com"
# Create a type for even integers
EvenInt <- create_type("even_int", function(x) {
is.integer(x) && all(x %% 2 == 0)
})
value %:% EvenInt %<-% 4L
try(value <- 5L) # Error: Type error
# Create a type that checks data frame structure
PersonDF <- create_type("person_df", function(x) {
is.data.frame(x) &&
all(c("name", "age") %in% names(x)) &&
is.character(x$name) &&
is.numeric(x$age)
})
Run the code above in your browser using DataLab