Skip to Content
R Programming By Example
book

R Programming By Example

by Omar Trejo Navarro
December 2017
Beginner to intermediate
470 pages
12h 29m
English
Packt Publishing
Content preview from R Programming By Example

Active bindings

Active bindings look like fields, but each time they are accessed, they call a function. They are always publicly visible and are similar to Python's properties. If we wanted to implement the color() method as an active binding, we could use the following code. As you can see, you can either get or set the color attribute, without using an explicit method call (note the missing parentheses):

R6Rectangle <- R6Class(
    "R6Rectangle",
    public = list(
        ...
    ),
    private = list(
        ...
    ),
    active = list(
        color = function(new_color) {
            if (missing(new_color)) {
                return(private$own_color)
            } else {
                private$own_color <- new_color
            }
        }
    )
)

R6_rectangle <- R6Rectangle$new(2, 3, "blue")
R6_rectangle$color
#> [1] "blue"
R6_rectangle$color <- "black" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Efficient R Programming

Efficient R Programming

Colin Gillespie, Robin Lovelace
R Programming

R Programming

Jared P. Lander

Publisher Resources

ISBN: 9781788292542Supplemental Content