Skip to content

Instantly share code, notes, and snippets.

@jimhester
Created Dec 4, 2017
Embed
What would you like to do?
Simple C style enum in R.
enum <- function(...) {
nms <- eval(substitute(alist(...)))
x <- as.list(setNames(seq_along(nms), nms))
f <- tempfile()
attach(x, name = f)
# Cleanup the enum if when the parent frame exists
# unless we are in the global environment.
if (!identical(parent.frame(), globalenv())) {
withr::defer(detach(name = f), parent.frame())
}
x
}
year <- enum(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
for (month in year) {
if (month > Aug) {
print(month)
}
}
#> [1] 9
#> [1] 10
#> [1] 11
#> [1] 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment