pearselab / r-intro-aspri951

r-intro-aspri951 created by GitHub Classroom
0 stars 1 forks source link

checking class of arguments #4

Open aspri951 opened 7 years ago

aspri951 commented 7 years ago

I am currently trying to make a constructor function for a polygon object. I want my function to check that everything the user inputs into the polygon function is actually class "point." However, using the line of code if(!inherits(first.point), "point | !inherits(second.point, "point")) does NOT check any points that are not defined arguments to the function (in other words, anything from the "..." section of the function). I tried to check the class of the arguments like this:

new.polygon <- function(first.point, second.point, ...){
  if(!inherits(args(new.polygon), "point")){
    stop("At least one object is not a point.")
  }
  polygon <- list(first.point, second.point, ..., first.point)
  class(polygon) <- "polygon"
  return(polygon)
}

But of course this doesn't work because this asks what the class of the arguments are as a whole, which is class "function." Next I tried if(!inherits(first.point, "point") | !inherits(second.point, "point") | ...), which similarly does not work, and tried if(!inherits(first.point, "point") | !inherits(second.point, "point") | !inherits(..., "point")), which... does not work. I'm not sure where to look from here, or how to find information on how to manipulate ellipses. Perhaps a more relevant question: is what I'm attempting to do actually possible in R?

willpearse commented 7 years ago

I actually showed you how to do this when you came to my office, so see if what's below jogs your memory.

demo <- function(x, ...){
    return(sapply(..., class))
}
demo(123, list(456, "789"))

...does that give you a hint?...