UofUEpiBio / PHS7045-advanced-programming

https://uofuepibio.github.io/PHS7045-advanced-programming
3 stars 4 forks source link

Week 7 #12

Closed gvegayon closed 1 month ago

gvegayon commented 1 year ago

Hey @UofUEpiBio/phs7045-2023, this week we will write R packages. Please come prepared having read the following:

chipmanj commented 1 year ago

@UofUEpiBio/phs7045-2023, I was hoping to be there today to zoom together in person, but I will not be able to do so. Also, it sounds like there will be poor winter weather later this afternoon. Please be careful if you choose to come in today.

hyejung0 commented 1 year ago

@gvegayon and @chipmanj I was trying to look into the chapter 3 and 2 to find out how to generate plot.function and summary.function functions, but I couldn't find it. What is this type of function called? Is there a name for it? How do I search for these additional functions?

chipmanj commented 1 year ago

@gvegayon and @chipmanj I was trying to look into the chapter 3 and 2 to find out how to generate plot.function and summary.function functions, but I couldn't find it. What is this type of function called? Is there a name for it? How do I search for these additional functions?

@hyejung0 : These functions are called "generic" functions. At the end of your function, assign a class to the object [className]. Then create a summary function called summary.[className] to create custom output. The summary function will work as desired for any object of the type [className]. The same can be done with commonly used functions, such as plot. Here's a small example:

myAdd <- function(v1, v2){
  o <- v1 + v2
  class(o) <- "anyName"
  return(o)
}

summary.anyName <- function(o){

  print(paste("the value is", o))

}

a <- myAdd(1,2)
class(a)
summary(a)
gvegayon commented 1 year ago

Thank you, @chipmanj. @hyejung0, more technical details can be found here. One important thing to add is that your method must contain the arguments of the generic function, for example, the plot() function has the following minimum arguments: x, y, ... (see ?base::plot), therefore, if you want to create a plot method for a class named anyName, the new function should have at least x, y, ... (even if you don't use them all), e.g.:

plot.anyName <- function(x, y, ...) {
  graphics::plot(x + 1)
}

The previous function only uses x, but y and ... are still required. If you don't include those arguments, you will receive a warning from R CMD check. HIH