Making subclass of list

非 Y 不嫁゛ 提交于 2019-12-22 09:49:45

问题


I have the following 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 would be proper solution to not lose the class by subsetting? FOr example, class(obj[1:2]) results in mysubclass and still behaves as a list.


回答1:


The problem is that the generic [ method is stripping off the class attribute. To avoid this, you could just define your own generic for mysubclass, i.e.

## Answer suggested by 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 the class attribute
    cl = class(x)
    ## Pass your object to the next method
    y = NextMethod('[')
    ## Update the class and return
    class(y) = cl
    y
}

Your examples now work as expected. You should also look at:

  • help('[')
  • methods('[')


来源:https://stackoverflow.com/questions/24284005/making-subclass-of-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!