Created
December 4, 2017 18:19
-
-
Save jimhester/27f206167715185a0f30e7c7828da845 to your computer and use it in GitHub Desktop.
Simple C style enum in R.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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