Dawei
Dawei

Reputation: 41

R: How to inherit a base data type (e.g. list, vector) in R

I'm trying to extend customized type (for example mylist) from a base type "list" in R, which contains all functions and prototype of R base "list". It should support below operators as "list":

a <- list(column1=c(1:5), column2=c(6:10))
aa <- mylist(column1=c(1:5), column2=c(6:10))
a$column1
1 2 3 4 5
aa$column1
1 2 3 4 5

All other usages of "list" in R is expected to be supported my "mylist"

My questions is : How could I create the "mylist" in R. Thanks for help.

Upvotes: 0

Views: 34

Answers (1)

baptiste
baptiste

Reputation: 77096

you can append your class before the list class,

mylist <- function(...){
  structure(list(...), class = c("mylist", "list"))
}


aa <- mylist(column1=c(1:5), column2=c(6:10))
aa$column1

plot.mylist <- function(x) image(volcano)
plot(aa)

Upvotes: 1

Related Questions