1

我在包中覆盖 setClass 和 setMethod 时遇到问题

要求:R 3.0.1,Rtools

请在下面找到重现问题的步骤:

1.创建类和方法

setClass(Class="AAA",
           representation(
           name="character",
           val="numeric"
         )
)

setMethod("*", 
      signature(e1 = "numeric", e2 = "AAA"), 
      definition=function (e1, e2) {
          e2@val = e2@val * e1
      e2       
    }
)

2/ 将文件保存在

C:\AAA.r

3/ 构建一个包

>  setwd("C:")
>  package.skeleton(name="AAA",code_files="C:\\AAA.r")
>  system("R CMD build AAA")
>  system("R CMD INSTALL --build AAA")

4/ 测试

> library(AAA)
> x = new("AAA")
> x@val = 100
> -1 * x
An object of class "AAA"
Slot "name":
character(0)

Slot "val":
[1] -100

Slot "type":
character(0)

5/ 覆盖类和方法

setClass(Class="AAA",
           representation(
           name="character",
           val="numeric",
           type="character",
           desc="character"
         )
)

setMethod("*", 
     signature(e1 = "numeric", e2 = "AAA"), 
                  definition=function (e1, e2) {
                    if (e2@type == "double"){
                        e2@val = e2@val * (2 * e1)       
                    } else {
                        e2@val = e2@val * e1 
                    }
                                 e2
                  }
        )

6/ 测试

> y = new("AAA")
> y@val=25
> y@type="double"
> -1 * y
Error in -1 * y : invalid object (non-function) used as method

请指教

4

0 回答 0