如何访问S4对象的方法

时间:2016-03-20 22:29:09

标签: r s4

我当前的项目是使用S4对象,我想访问python或C中的泛型方法。这是示例

setClass("Account",
         representation(balance = 'numeric', holder = 'character'),
         prototype = prototype(balance = NA_real_, holder = NA_character_),
         validity = function(object) {
           if (object@balance < 10) {
             return("The start balance should not be negative")
           }
           return(TRUE)
         })

setMethod("show", signature = "Account",
          definition = function(object) {
            cat("The account holder is", object@holder, "\n")
            cat("The account balance is", object@balance, "\n")
          })

setGeneric("deposit", def = function(.Object, amount) {
  standardGeneric("deposit")
})

setMethod("deposit", signature = "Account",
          definition = function(.Object, amount) {
            nameObject <- deparse(substitute(.Object))
            .Object@balance <- .Object@balance + amount
            assign(nameObject, .Object, envir = parent.frame())
            return(invisible())
      })

目前我可以使用以下内容:

acc <- new("Account", balance = 10, holder = "nal-ra")
deposit(acc, 20)
acc
#> The account holder is nal-ra 
#> The account balance is 30 

我想使用acc$.$deposit(20)代替deposit(acc, 20)

我知道引用类和R6类可以完成这项工作,但我的项目无法使用它们。

1 个答案:

答案 0 :(得分:2)

S4方法不起作用。相反,更新并返回对象

setMethod("deposit", signature = "Account",
    definition = function(.Object, amount) {
        .Object@balance <- .Object@balance + amount
        .Object
})

acc = deposit(acc, 20)

另一种表述是编写deposit<-替换方法

setGeneric("deposit<-", function(x, value) standardGeneric("deposit<-"))
setReplaceMethod("deposit", c("Account", "numeric"), function(x, value) {
    x@balance <- x@balance + value
    x
})

> acc <- new("Account", balance = 10, holder = "nal-ra")
> deposit(acc) <- 20
> acc
The account holder is nal-ra 
The account balance is 30