r - Making subclass of list -
i have next code
obj <- list(list(a=4,f=5,g=5),list(a=44,f=54,g=54)) class(obj) <- "mysubclass" class(obj[1]) class(obj[2]) class(obj[1:2]) class(obj)
resulting in:
> class(obj[1]) [1] "list" > class(obj[2]) [1] "list" > class(obj[1:2]) [1] "list" > class(obj) [1] "mysubclass"
what proper solution not lose class subsetting? example, class(obj[1:2])
results in mysubclass
, still behaves list.
the problem generic [
method stripping off class
attribute. avoid this, define own generic mysubclass
, i.e.
## reply suggested petr matousu ## based on simple.list method '[.mysubclass' = function(x, i, ...) { structure(nextmethod("["), class = class(x)) }
or
'[.mysubclass' = function(x, i, j, ..., drop=true) { ## store class attribute cl = class(x) ## pass object next method y = nextmethod('[') ## update class , homecoming class(y) = cl y }
your examples work expected. should at:
help('[')
methods('[')
r r-s3
No comments:
Post a Comment