qed
qed

Reputation: 23104

Same method for multiple classes in R

I often encounter scenarios where I wish to have the same method for two classes, when they are similar enough. For example:

func.matrix = function(m) {
stopifnot(ncol(m) == 2)
c(mean(m[, 1]), sd(m[, 2]))
}

func.data.frame = function(m) {
stopifnot(ncol(m) == 2)
c(mean(m[, 1]), sd(m[, 2]))
}

How can I save the redundancy?

Upvotes: 7

Views: 395

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

If both functions are actually the same, then you can do something like this to save yourself some typing at least:

func.matrix <- func.data.frame <- function(m) {
  stopifnot(ncol(m) == 2)
  c(mean(m[, 1]), sd(m[, 2]))
}
func.matrix
# function(m) {
# stopifnot(ncol(m) == 2)
# c(mean(m[, 1]), sd(m[, 2]))
# }
func.data.frame
# function(m) {
# stopifnot(ncol(m) == 2)
# c(mean(m[, 1]), sd(m[, 2]))
# }

The other alternative, as you mentioned in the comment, would be to move the common part out into a function of its own (refactoring, I guess it's called?) and call that within your functions.

Upvotes: 9

Related Questions