Skip to content

Instantly share code, notes, and snippets.

@jimhester
Created December 4, 2017 18:19
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jimhester/27f206167715185a0f30e7c7828da845 to your computer and use it in GitHub Desktop.
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