0

I defined a member function for an S4 class (programming language R) which is supposed to add elements to a list, but it does nothing:

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()

This will print an empty list. What is going on here?

gcc
  • 120
  • 8

1 Answers1

1

add function is the problem : what you want to do is passing an object ListHolder into the function and modify it, which R does not support.

So, in your code above:

  1. setMethod: add(Object, i), add return(this) statement at the end of function add.
  2. testListHolder: replace lh after add, for(i in 1:10) lh <- add(lh,i)

EDIT: also check this(use function to modify an object) question

Community
  • 1
  • 1
xtluo
  • 1,961
  • 18
  • 26