0

We all know functions like is.data.frame or is.double etc. Probably easy to do but hard to google: How can create your own is.? function? Is there a better way to do it then:

is.myClass <- function(x){
if(class(x) %in% "myClass") return(TRUE)
else return(FALSE)
}
2
  • This question seems related: stackoverflow.com/questions/5158830/…
    – Chase
    Nov 28, 2012 at 16:23
  • I think that should go the other way around: function(x) {"myClass" %in% class(x)}, but as @James points out inherits is more idiomatic (I don't know whether it has any other advantages)
    – Ben Bolker
    Nov 28, 2012 at 16:32

1 Answer 1

4

Perhaps inherits is enough:

is.myClass <- function(x) {inherits(x,"myClass")}

x <- 1
is.myClass(x)
[1] FALSE
class(x) <- c(class(x),"myClass")
is.myClass(x)
[1] TRUE
3
  • You don't need { and } for single line functions
    – hadley
    Nov 28, 2012 at 16:44
  • @hadley force of habit. Can't remember if the intepreter imposes a penalty for using them.
    – James
    Nov 28, 2012 at 16:52
  • 2
    remembering whether or not there is a interpreter penalty is a waste of time; it just looks ugly to my eyes
    – hadley
    Nov 28, 2012 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.