Nova
Nova

Reputation: 618

What is the difference between new() and setClass() in R?

I am curious as to what the functional difference is between between new() and setClass() in R?

I answered another question that seems to suggest that they operate identically, except that new() is potentially far less "restrictive."

Upvotes: 0

Views: 560

Answers (2)

JDL
JDL

Reputation: 1654

The two functions have completely different side effects. You need to call setClass when you are defining a class. You can't just do

new("square",x=0,y=0,side=1) -> mySquare

and expect R to know what a square is (you will get an error along the lines of "undefined class 'square'"). If you do

setClass("square",
  slots=c(
    x="numeric",
    y="numeric",
    side="numeric"
  )
) -> square

mySquare <- square(x=0,y=0,side=1)

then you have defined the class square and can then call the function square to create objects from it. You can also at this point call new("square",...) as well but the effect is the same.

If you want to create a constructor function that doesn't just take slot names as arguments, then the recommended approach is to create an ordinary function along the lines of

createSquare <- function(r,theta,side){
  square(x=r*cos(theta),y=r*sin(theta),side=side)
}

Upvotes: 0

vvilin
vvilin

Reputation: 192

You can refer to this link in the description on top of the page and the Value section: r documentation setClass

From the link:

  • A generator function suitable for creating objects from the class is returned, invisibly. A call to this function generates a call to new for the class. The call takes any number of arguments, which will be passed on to the initialize method. If no initialize method is defined for the class or one of its superclasses, the default method expects named arguments with the name of one of the slots and unnamed arguments that are objects from one of the contained classes.

  • Typically the generator function is assigned the name of the class, for programming clarity. This is not a requirement and objects from the class can also be generated directly from new. The advantages of the generator function are a slightly simpler and clearer call, and that the call will contain the package name of the class (eliminating any ambiguity if two classes from different packages have the same name).

  • If the class is virtual, an attempt to generate an object from either the generator or new() will result in an error.

Upvotes: 2

Related Questions