R S4 class,成员函数没有作用

R S4 class, member function has no effect

我为 S4 class(编程语言 R)定义了一个成员函数,它应该向列表添加元素,但它什么也没做:

setClass("ListHolder",
representation(
    .list   = "list"
),
prototype(
    .list   = list()
))
setGeneric("add",
function(this,i) standardGeneric("add")
)
setMethod("add",
signature(this="ListHolder",i="numeric"),
definition = function(this,i){

    k <- length(this@.list)
    this@.list[[k+1]] <- i
})

testListHolder <- function(){

    lh <- new("ListHolder")  
    for(i in 1:10) add(lh,i)
    print(lh@.list)
}

testListHolder()

这将打印一个空列表。这是怎么回事?

add 函数是问题所在:您想要做的是将对象 ListHolder 传递给函数并修改它,R不支持。

因此,在您上面的代码中:

  1. setMethod: add(Object, i),在函数末尾添加return(this)语句添加.
  2. testListHolder:add后替换lh,for(i in 1:10) lh <- add(lh,i)

编辑: 还要检查 this(使用函数修改对象)问题