Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 191

6.2.2 Creating Generic Methods

Оглавление

We already saw how to create a method for a generic function by using simply the right naming convention. To add a new generic function, it is sufficient to call UseMethod().

UseMethod()

UseMethod() takes two arguments: the name of the generic function, and the argument to use for the method dispatch. If you omit the second argument it will dispatch on the first argument to the function. There is no need to pass any of the arguments of the generic to UseMethod(), R will take care of that for you.

# add_balance # Dispatcher function to handle the action of adding a given amount # to the balance of an account object. # Arguments: # x -- account -- the account object # amount -- numeric -- the amount to add to the balance add_balance <- function(x, amount) UseMethod(“add_balance”)

This construct will do nothing else than trying to dispatch the real action to other functions. However, since we did not program them yet, there is nothing to dispatch to. To add those methods, it is sufficient to create a function that has the right naming convention.

# add_balance.account # Object specific function for an account for the dispatcher # function add_balance() # Arguments: # x -- account -- the account object # amount -- numeric -- the amount to add to the balance add_balance.account <- function(x, amount) { x[[2]] <- x[[2]] + amount; # Note that much more testing and logic can go here # It is not so easy to pass a pointer to a function so we # return the new balance: x[[2]]} my_curr_acc <- add_balance(my_curr_acc, 225) print(my_curr_acc) ## [1] 325

Leaving the code up to this level is not really safe. It is wise to foresee a default action in case the function add_balance() is called with an object of another class.

# add_balance.default # The default action for the dispatcher function add_balance # Arguments: # x -- account -- the account object # amount -- numeric -- the amount to add to the balance add_balance.default <- function(x, amount) { stop(“Object provided not of type account.”) }

The Big R-Book

Подняться наверх