How to assess in an R S4 list of child objects a parent object

42 Views Asked by At

I have a parent S4 class with a list of child S4 subclasses and a parent feature. I try to make a generic child method that immediately retrieves the parent feature although it is in a list.

Here is what I tried.

setClass("Parent", slots = c(childrens="list", parentfeat="character"))
setClass("Child", slots = c(drunk="numeric", grade="character", jokes="numeric"))

setGeneric("drunkenJokes", function(Child, ...) standardGeneric("drunkenJokes"))

setMethod("drunkenJokes", c("Child"), function(
  Child, 
  doSayHi = F, 
  parentfeat = parentfeat # I want to automatically grab the parent feat when it exists
){
  if(doSayHi){message("Hi")}
  print(paste("Parentfeat, parent = ",parentfeat,sep=""))
  return(Child@drunk * Child@jokes)
})

# two kids, never drunk, high grades, great jokes
son <-new("Child", drunk=0, grade="A", jokes=9)
daughter <-new("Child", drunk=0, grade="A", jokes=10)
# an orfan, no funny life
orfan <- new("Child", drunk=0, grade="A", jokes=0)

# Got it from the parents
parent <-new("Parent", childrens=list(kid1=son,kid2=daughter), parentfeat="Best In the World")
# But the orfan has no parents

# Works with an orfan
drunkenJokes(orfan, doSayHi = T, parentfeat="NoParentsToRelyOn")
# [1] "Parentfeat, parent = NoParentsToRelyOn"
# [1] 0


# Can't get the parent feat ... because in a list or..?
drunkenJokes(parent@childrens[[1]], doSayHi = T)
# Hi
# Error in h(simpleError(msg, call)) : 
#   error in evaluating the argument 'x' in selecting a method for function 'print': promise already under evaluation: recursive default argument reference or earlier problems? 
0

There are 0 best solutions below