rjss
rjss

Reputation: 1013

Common operations between multiple S3 methods

I recently (very) started looking into creating S3 functions in R. I am working in a function where I foresee having common operations between different methods. Not sure how this should be done. For example:

myfun <- function (x) {
UseMethod("myfun")
}

myfun.numeric <- function(x) {
  a<-x+5
  b<-a^2
  c<-b+4
  d<-c-3
  d
}

myfun.character <- function(x) {
  a<-as.numeric(x)+9
  b<-a^2
  c<-b+4
  d<-c-3
  d
}

myfun("3")
myfun(3)

The function at this time is not too long. I guess technically I can have a function that perform the part represented by letter "a" then have a common function that perform steps "b", "c", and "d". In some cases the functions could be quite short and having an additional function seems not to be the best practice. What is usually done in cases like this?

Upvotes: 4

Views: 54

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269526

Here are two possibilities. There is some danger in using the default method since it might get invoked in unanticipated situations so the common function seems more reliable but either would work in the example you show.

1) default method Put the common code in the default method and use NextMethod().

myfun <- function (x) UseMethod("myfun")

myfun.numeric <- function(x) {
  x<-x+5
  NextMethod()
}

myfun.character <- function(x) {
  x <-as.numeric(x)+9
  NextMethod()
}

myfun.default <- function(x) {
  b<-x^2
  c<-b+4
  d<-c-3
  d
}

myfun("3")
myfun(3)

2) common function Alternately just put the common code in a separate function called common, say, and call it.

myfun <- function (x) UseMethod("myfun")

myfun.numeric <- function(x) {
  y <-x+5
  common(y)
}

myfun.character <- function(x) {
  y <-as.numeric(x)+9
  common(y)
}

common <- function(x) {
  b<-x^2
  c<-b+4
  d<-c-3
  d
}

myfun("3")
myfun(3)

Upvotes: 1

Related Questions