What is distinction between initialize method vs prototype in setClass to set default values for S4 class?

,

In R S4 OOP, I'm aware of 2 ways so set default values for a particular class.

1.) Using prototype in setClass()

setClass("Person",
         slots = c(
           name = "character",
           age = "numeric"
         ), 
         prototype = list(
           name = "Jim",
           age = 25
         )
         )

2.) Using initialize in setMethod()

setMethod("initialize", "Person",
          function(.Object,
                   name,
                   age,
                   ...) {
              .Object@name <- "Jim"
              .Object@age <- 25
            validObject(.Object)
            return(.Object)
          }
)

assign("Person", Person, envir = .GlobalEnv)

Can anyone please elaborate on the distinction between these two i.e. why would we want to include a separate initialize method vs using prototype() in setClass() ? What is S4 best practice?

Thank you in advance for the response.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.