The enum
package provides a robust implementation of enumerations
(enums) for R, enabling the creation of type-safe, validated sets of
named constants. Enums help prevent errors by constraining variables to
predefined values and offer better code readability and maintainability.
You can install the development version of enum from GitHub with:
# install.packages("pak")
pak::pak("milanmlft/enum")
library(enum)
# Create an enum for days of the week
Days <- Enum(
MONDAY = 1,
TUESDAY = 2,
WEDNESDAY = 3,
THURSDAY = 4,
FRIDAY = 5,
SATURDAY = 6,
SUNDAY = 7
)
# Use the enum
today <- Days$MONDAY
today
#> [1] 1
- Validation: Values are automatically validated against defined constants
- Readability: Named constants make code more self-documenting
- Maintainability: Centralized definition of related constants
Enums support the following accessors:
$
: Access a single value by name[[
: Access multiple values by namenames
: Get the names of the enum
Days[["MONDAY"]]
#> [1] 1
Days$TUESDAY
#> [1] 2
names(Days)
#> [1] "MONDAY" "TUESDAY" "WEDNESDAY" "THURSDAY" "FRIDAY" "SATURDAY"
#> [7] "SUNDAY"
All enum names must be unique and non-empty strings.
Days <- Enum(
MONDAY = 1,
MONDAY = 2
)
#> Error: Duplicate enum names
Days <- Enum(
MONDAY = 1,
2
)
#> Error: All enum values must be named
Enums are immutable, meaning that once created, their values cannot be changed.
Days$MONDAY <- 8
#> Error: Cannot modify enum
This package uses pre-commit hooks to ensure code quality. To set up the development environment:
# Install pre-commit
pip install pre-commit
# Install the hooks
pre-commit install
# Run hooks manually
pre-commit run --all-files
This project is licensed under the MIT License - see the LICENSE file for details.