简体   繁体   中英

Creating S3 methods in R

for an advanced programming in R class we've been asked to create a package. The package is to include a function, "lad", a dataset, "area", and 3 methods, "print.lad", "coef.lad", and "predict.lad".

I have my "lad" function saved, and when building/requiring my package the function runs just fine. However, I'm a bit confused on the usage of setMethod.

For example, I created a new .R script titled "print.lad" in my "R" folder within the package. This method is to write the coefficient vector from the output of "lad" to the console. We've been instructed to make the output of "lad" a list of type "lad" with "coefficients" being the first in the list.

We've never gone over methods in class, so I had to look around on the internet for help. After the information/parameters/etc section, my code for "print.lad" looks like this:

setMethod("print", "lad", function(object){
  print(object$coefficients)
} )

I can see that this isn't correct, but I'm also puzzled as to how to apply this setMethod function. I don't wish for someone to give me a working chunk of code outright, but an example of the application of setMethod and a bit of insight would be greatly appreciated. Thank you!

Create an object:

object <- list(coefficients = c("a" = 3, "b" = 4))

Assign the object a class:

class(object) <- "lad"

S3 methods have the form function.class . To define a "print" method:

print.lad <- function(object) {
  print("Here are the coefficients:")
  print(object$coefficients)
}

S3 methods are then automatically dispatched based on the object's class

print(object)
# [1] "Here are the coefficients:"
# a b 
# 3 4 

As an aside, I think I read somewhere that you should define print methods using cat instead of print because it's easier to control and nest, but I can't seem to find the source for that. For small cases, it shouldn't matter much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM