[R-sig-Geo] C API for sp classes?

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Tue Mar 7 17:24:12 CET 2006


Wouter Buytaert wrote:

> The resulting R function doesn't seem very complicated. I'm a newbie 
> though, so all recommendations welcome:
> 
> topidx <- function(map) {
> 
> if(!(class(map) == "SpatialGridDataFrame"))
>  	printf("Map should be of SpatialGridDataFrame class")
>

  Recommendation number 1 - read all about Object-Oriented Programming!

  You shouldn't have a function that tests the class of an object, you 
should write a generic function and a method for your class.

  With S3 methods this was easy, you wrote a generic function called 
'topidx' and then a method for SpatialWhateverObject called 
topidx.SpatialWhateverObject. Then your topidx.SpatialWhateverObject() 
function could be pretty sure it was getting something that was a 
SpatialWhateverObject. I've never got my head round the new S4 class 
stuff, but sp uses it widely so check out Edzer's code, he's a master :)

  The reason explicit checks for class(foo) are wrong is because your 
object might not be of that class, but might inherit from that class, ie 
be a superclass of SpatialGridDataFrame. Add to that the fact that 
class() can be a vector:

  > class(glm(y~x))
  [1] "glm" "lm"

  If you really have to check to see if the object you are being passed 
is of the right sort, use 'inherits':

  > inherits(glm(y~x),'lm')
  [1] TRUE
  > inherits(glm(y~x),'glm')
  [1] TRUE

This should be sufficient to guarantee that the object implements the 
functionality you need to do your work.

Otherwise, I vote for .Call() :)

  Barry




More information about the R-sig-Geo mailing list