alittleboy
alittleboy

Reputation: 10966

retain a class attribute of an R object when subsetting

I have an R object called gene_table, and it has class foo. Now I subset this gene_table by

gene_data = gene_table[1:100,1:5]

However, when I call class(gene_data), it is no longer of class foo, but instead, it has class matrix. This is a headache for me because my method summary.foo won't recognize this object gene_data of class matrix. I am hoping to retain the original class attribute when subsetting, so could anyone tell me how to do it? Thanks!

Update: dput(head(gene_table)) gives me

c(5.21708054951994, 5.01224214039806, 4.92160314073853, 4.83031021496, 4.78552614584879, 4.77821370665578)

and str(gene_table) gives me

 foo [1:22743, 1:2] 5.22 5.01 4.92 4.83 4.79 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:22743] "ENSG00000127954" "ENSG00000151503" "ENSG00000096060" "ENSG00000091879" ...
  ..$ : chr [1:2] "Var1" "Var2"

Upvotes: 9

Views: 455

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176688

You could use something like this as your definition for [.foo:

`[.foo` <- function(x, ..., drop=TRUE) {
   structure(NextMethod(), class="foo")
}

You may need to add other things, depending on the complexity of your "foo" class.

Upvotes: 7

Related Questions