Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same method for multiple classes in R

Tags:

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?

like image 882
qed Avatar asked Oct 15 '13 16:10

qed


1 Answers

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.

like image 165
A5C1D2H2I1M1N2O1R2T1 Avatar answered Nov 15 '22 00:11

A5C1D2H2I1M1N2O1R2T1