Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common operations between multiple S3 methods

Tags:

methods

r

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?

like image 554
rjss Avatar asked Jan 19 '26 18:01

rjss


1 Answers

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)
like image 114
G. Grothendieck Avatar answered Jan 21 '26 07:01

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!