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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With