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"
Subsetting in R is a useful indexing feature for accessing object elements. It can be used to select and filter variables and observations. You can use brackets to select rows and columns from your dataframe.
There are three subsetting operators, [[ , [ , and $ . Subsetting operators interact differently with different vector types (e.g., atomic vectors, lists, factors, matrices, and data frames). Subsetting can be combined with assignment.
The way you tell R that you want to select some particular elements (i.e., a 'subset') from a vector is by placing an 'index vector' in square brackets immediately following the name of the vector. For a simple example, try x[1:10] to view the first ten elements of x.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With