knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

enum

Lifecycle: experimental

Installation

remotes::install_github("shunsambongi/enum")

Example

library(enum)

clrs <- enum(
  NAVY    = "#001F3F",
  BLUE    = "#0074D9",
  AQUA    = "#7FDBFF",
  TEAL    = "#39CCCC",
  OLIVE   = "#3D9970",
  GREEN   = "#2ECC40",
  LIME    = "#01FF70",
  YELLOW  = "#FFDC00",
  ORANGE  = "#FF851B",
  RED     = "#FF4136",
  MAROON  = "#85144B",
  FUCHSIA = "#F012BE",
  PURPLE  = "#B10DC9",
  BLACK   = "#111111",
  GRAY    = "#AAAAAA",
  SILVER  = "#DDDDDD",
  WHITE   = "#FFFFFF"
)

print(clrs)

scales::show_col(clrs, labels = FALSE)

Extracting values

You can extract values from the enum in many different ways. Notice that we are not subsetting, just extracting.

clrs["RED", "GREEN", "BLUE"]

clrs$RED

clrs[["RED"]]

"#FFFFFF" %in% clrs

enum_extract(clrs, c("GREEN", "YELLOW"))

enum_keys(clrs)

enum_vals(clrs)

Updating values

You can update enum values if you really need to. However, you can't add or remove keys.

abc <- enum(A = "a", B = "b", C = "c")

abc <- enum_update(abc, C = "sea") # you need to reassign
abc 

abc$B <- "bee" # this is inplace
abc

ggplot2

enums can be used in many ways with ggplot2, for example with manual scales.

library(ggplot2)

plot <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, color = Species)) + 
  geom_point() +
  theme_bw()

plot + scale_color_manual(values = clrs)

plot + scale_color_manual(values = clrs["RED", "GREEN", "BLUE"])

plot + scale_color_manual(values = with_enum(clrs, c(
  setosa = PURPLE, 
  versicolor = ORANGE, 
  virginica = YELLOW
)))


iris_clrs <- enum(
  setosa = clrs$AQUA, 
  versicolor = clrs$FUCHSIA, 
  virginica = clrs$LIME
)
plot + scale_color_manual(values = enum_vec(iris_clrs))

dbplyr

enums also work in sql queries using dbplyr

library(dplyr, warn.conflicts = FALSE)
library(dbplyr, warn.conflicts = FALSE)

df <- lazy_frame(
  color = "red"
)

df %>%
  filter(color %in% clrs) %>%
  show_query()


df %>%
  filter(color %in% !!clrs["RED", "BLUE"]) %>%
  show_query()


shunsambongi/enum documentation built on Nov. 11, 2019, 6:46 a.m.