akh22
akh22

Reputation: 701

Overcome error adding dimnames of dgRMatrix in R

I have a dgRMatrix as follows;

str(ann.mini$layers['spliced'])
List of 1
 $ spliced:Formal class 'dgRMatrix' [package "Matrix"] with 6 slots
  .. ..@ p       : int [1:14663] 0 809 1245 1730 2550 3061 3825 4464 6114 6458 ...
  .. ..@ j       : int [1:11655258] 133 185 245 287 320 427 467 580 598 649 ...
  .. ..@ Dim     : int [1:2] 14662 55414
  .. ..@ Dimnames:List of 2
  .. .. ..$ : NULL
  .. .. ..$ : NULL
  .. ..@ x       : num [1:11655258] 1 1 1 3 1 1 5 1 1 1 ...
  .. ..@ factors : list()

As you can see, both Dimnames are null. I tried to add Dimnames to this dgRMatrix by following;

dimnames(ann.mini$layers['spliced'])<-list(rownames(ann.mini$X), colnames(ann.mini$X))

but I get a following error message;

Error in dimnames(ann.mini$layers["spliced"]) <- list(rownames(ann.mini$X),  : 
  'dimnames' applied to non-array 

Length of rownames() and colname() match the dimension of the dgRMatrix in question;

> length(colnames(ann.mini$X))
[1] 55414
> length(rownames(ann.mini$X))
[1] 14662

and str of the matrix, "X" is ;

str(ann.mini$X)
Formal class 'dgRMatrix' [package "Matrix"] with 6 slots
  ..@ p       : int [1:14663] 0 809 1245 1730 2550 3061 3825 4464 6114 6458 ...
  ..@ j       : int [1:11655258] 133 185 245 287 320 427 467 580 598 649 ...
  ..@ Dim     : int [1:2] 14662 55414
  ..@ Dimnames:List of 2
  .. ..$ : chr [1:14662] "AAACCCAAGCCTTTGA" "AAACCCAAGCGGATCA" "AAACCCACACCATATG" "AAACCCACACCTGCAG" ...
  .. .. ..- attr(*, "name")= chr "barcode"
  .. ..$ : chr [1:55414] "ENSMUSG00000102628.2" "ENSMUSG00000100595.2" "ENSMUSG00000097426.2" "ENSMUSG00000104478.2" ...
  .. .. ..- attr(*, "name")= chr "gene_id"
  ..@ x       : num [1:11655258] 1 1 1 3 1 1 5 1 1 1 ...
  ..@ factors : list()

Basically, I'd like to create exactly the same Dimname in the dGrMatrix, "X" in the "splice" dgRMatrix. I really do appreciate any pointers.

Upvotes: 0

Views: 101

Answers (1)

Mikael Jagan
Mikael Jagan

Reputation: 11326

You seem to have confused the subset operator [ and the element operator [[. ann.mini$layers["spliced"] is a list whose first element is a dgRMatrix. The list is not a matrix, so you cannot give it a dimnames attribute. Try this instead:

dimnames(ann.mini$layers[["spliced"]]) <- dimnames(ann.mini$X)

The differences between [ and [[ are documented in ?Extract.

Upvotes: 1

Related Questions