math
math

Reputation: 2022

how to export classes (S4) in R using roxygen

I built an example:

            #'  class foo
            #'  
            #'  Is basic class for testing
            #'  
            #'  @slot Name a character. 
            #'  @export foo

            foo <- setClass(Class = "foo",
                             slots = c(Name = "character"),prototype = list(Name = character())
            )


            #' foo
            #' 
            #' Tis is a basic constructor for testing
            #' 
            #'  @param Name a character
            #'  
            #'  @export
            #' 

            if(!isGeneric("foo")){
              setGeneric(name = "foo",
                         def = function(Name_ = "default")
                         {
                           standardGeneric("foo")
                         })
            }

            setMethod(f = "foo", signature(Name_ = "character"), 

                      definition = function(Name_)
                      {
                        return(new(Class = foo, Name = Name_))
                      }
            )

Then in another file I defined a setter/getter:

            #' Getter and setter
            #' 
            #' Getter and setter for the class foo (test)
            #' 
            #'  
            #'  @export
            #' 

            if(!isGeneric("getname")){
              setGeneric(name = "getname",
                         def = function(theObject)
                         {
                           standardGeneric("getname")
                         })
            }

            setMethod(f = "getname", signature(theObject = "foo"), 

                      definition = function(theObject)
                      {
                        return(theObject@Name)
                      }
            )

However when I run 'devtools::load_all()' I always get the error:

in method for ‘getname’ with signature ‘theObject="foo"’: no definition for class “foo”.

How can do I correctly export a S4 class. I followed the tutorial by Hadley Wickham. I want that people can built instances of my class but not extend it.

Upvotes: 2

Views: 1264

Answers (1)

Pablo
Pablo

Reputation: 368

When a type constraint is a class from another package, write @import <package_name> before setMethod, where package_name is the package in which the class is defined. If the class belongs to the same package, as in your question, you have to write @include <file.R> to make sure roxygen has processed your class definition file before using the class as a constraint.

Hope it helps

Upvotes: 2

Related Questions