0

I dont know how to deal with the name of a generic function, e.g.

     setClass(Class = "ABC",
              representation = representation(a="numeric")
     ) 
     ABC<-function(a=1){new("ABC",a=a)}
     setGeneric("geta", function(object) standardGeneric("geta"))
     setMethod("geta", signature = "ABC", definition = function(object) object@a)
     a<-ABC()
     geta(a)
     geta<-4
     geta(a)#Error: could not find function "geta"

You see what I mean, there function get lost or is being overwritten by the definition of geta<-4.

Klaus
  • 1,946
  • 3
  • 19
  • 34
  • 1
    Indeed you overwrite youre function by the definition of `geta<-4`. Why are you doing that? – Sander Van der Zeeuw Jun 14 '13 at 10:32
  • ALso you forgot to put a ) new version of function ABC `ABC<-function(a=1){new("ABC",a=a)}` – Sander Van der Zeeuw Jun 14 '13 at 10:33
  • What's the point? You can override any function by doing things like `sin<- 1/137` – Carl Witthoft Jun 14 '13 at 11:49
  • Because I want to use the same name for functions and variables, it should be possible. e.g. you load a package wich provides the function foo among others. And you declare a variable foo in your code, than for usual there is no conflict. – Klaus Jun 14 '13 at 12:09
  • 1
    Bad programming practice. I strongly recommend against doing that. There's no upside and, as you can see a strong downside. – Carl Witthoft Jun 14 '13 at 13:29
  • 2
    "you load a package wich provides the function foo" That's the key part right there. The only reason what you describe "works" is because the function is registered in a namespace that is attached to the search path. Then when R looks for the function, it doesn't find it in the global environment, it moves on to the available namespaces. In your example, the function only existed in the global environment in the first place. Regardless, this isn't a good idea, for the obvious reasons. – joran Jun 14 '13 at 14:08
  • Okay, but thats new for me, I know its not usual to use same name for a variable and a function in the same procedure, but normaly it should be possible, if S4 would work like a ordenary class definition of a high programming language. In this case geta would be a function of class ABC, and if I would initialise an object of ABC in my main procedure, there should be no way to overwrite the function geta, by a normal declaration of a object with name "geta". – Klaus Jun 14 '13 at 16:08
  • So would you like to explain me, how to use the function `geta.ABC<-function(object){object@a}` like an object-orientated function of an instance of class ABC? I imagened that setGenric and setMethod would manage this process, but in this way it should be not possible to overwrite the methode geta.ABC of class ABC by a simple declaration of a arbitrary object with the same name. – Klaus Jun 16 '13 at 10:43

0 Answers0