A package I am developing contains an R method, and have a function that I wish to apply to numeric matrices only.
My function will call a C function that expects a numeric matrix as its input. I want to make it easy for authors of other packages to write separate handlers for (say) numeric vectors or character matrices without having to edit the function in my package.
For the sake of a simple example, let's say I want the function to add one to matrices:
AddOne <- function (x) UseMethod('AddOne')
AddOne.[numeric-AND-matrix] <- function (x) add_one_in_c(x)
AddOne(1) # Should report "No applicable method"
AddOne(matrix("one")) # Should report "No applicable method"
AddOne(matrix(1)) # Should send the matrix to add_one_in_c()
Just looking to see whether x is a numeric, or a matrix, is too general:
AddOne <- function (x) UseMethod('AddOne')
AddOne.numeric <- function (x) message("X is numeric, but may not be a matrix")
AddOne.matrix <- function (x) message("X is a matrix, but may not be numeric")
And I've been discouraged from using inherits for this sort of purpose:
AddOne <- function (x) UseMethod('AddOne')
AddOne.matrix <- function (x) {
if (inherits(x, 'numeric')) {
add_one_in_c(x)
} else {
NextMethod(x)
}
}
This last solution would also be difficult to extend. Perhaps someone else could handle character matrices by writing AddOne.character(), but this function would also have to handle character vectors.
Is there a way to do this that takes full advantage of the Methods protocols?