19.4 Introducing ggproto

It’s essentially a list of functions

String <- list(
  add = function(x, y) paste0(x, y),
  subtract = function(x, y) gsub(y, "", x, fixed = TRUE),
  show = function(x, y) paste0(x, " and ", y)
)
Number <- list(
  add = function(x, y) x + y,
  subtract = function(x, y) x - y,
  show = String$show
)
String$add("a", "b")
[1] "ab"
String$subtract("june", "e")
[1] "jun"
String$show("ggplot", "bookclub")
[1] "ggplot and bookclub"
Number$add(1, 2)
[1] 3
Number$subtract(10, 5)
[1] 5
Number$show(1, 2)
[1] "1 and 2"

19.4.1 ggproto syntax

From the book:

Person <- ggproto("Person", NULL,
  first = "",
  last = "",
  birthdate = NA,
  
  full_name = function(self) {
    paste(self$first, self$last)
  },
  age = function(self) {
    days_old <- Sys.Date() - self$birthdate
    floor(as.integer(days_old) / 365.25)
  },
  description = function(self) {
    paste(self$full_name(), "is", self$age(), "old")
  }
)

19.4.2 ggproto style guide

Kind of dense - can read through on your own but most can be picked up as we read the rest of the book.