Reputation: 1529
How can I implement the generic function names for my S3 class so I can "set" the names of my object.
To retrieve the names I simply implemented it as:
names.myobject <- function(x, ...){
x$y
}
and then I can do:
names(myobject)
But I can't use it to set the names in the form of:
names(myobject) <- "a"
I'm thinking to something like:
names.myobject <- function(x, newname){
x$y <- newnames
}
How can implement the "set" form of names?
Upvotes: 2
Views: 111
Reputation: 46866
Figure out the signatures of the generics from the functions; the 'setter' is names<-
.
> names
function (x) .Primitive("names")
> `names<-`
function (x, value) .Primitive("names<-")
names
and names<-
are so-called primitive functions, with method dispatch implemented in C, so the usual indication that you're working with an S3 generic (UseMethod("foo")
in the body of the generic) is not present.
Implement methods following the pattern generic.class = function...
. Remember that the return value of the setter method needs to be the object that you've updated
names.myobject <- function(x) x$y
`names<-.myobject` <- function(x, value) { x$y = value; x }
Upvotes: 5