1

I have a list of dgCMatrix objects, and I want to edit a specific vector within each object to have an iterative suffix, a new one for each object. My objects look like this: dgCMatrix Object within list

the vector I want to add a suffix to is the second dim name vector, the cell barcodes.

I've been trying to do it like this:

#give the cell names a unique suffix for each matrix
counter <- 0
my_sparse_matrices <- lapply(my_sparse_matrices, function(matrix) {
  
  counter <<- counter + 1
      
  colnames(matrix$`Gene Expression`) <- paste0(colnames(matrix$`Gene Expression`),"_",counter)
})

But this seems to save the changed vector to my_sparse_matrices, when really I want to change each vector within the already existing my_sparse_matrices object.

I am doing this because I am trying to aggregate all these single cell expression matrices into one rLiger object, which requires a list of sparse matrices. However, the cells cannot have the same name between matrices, hence the need for a unique suffix for each one. Can anyone help me out what I need to do to make this happen? I am still relatively new to using lapply.

JonahD
  • 11
  • 3

1 Answers1

0

You don't really need a loop or vectorization here. If you were to check the attributes of your list:

attributes(my_sparse_matrices)

You will see a list of all names of these matrices.

To change the names:

attributes(my_sparse_matrices) <- list(
   names = paste0("Gene Expression_", 
                  1:length(my_sparse_matrices)))

Since your question isn't reproducible, I made some data to validate this.

library(Matrix)

(m <- Matrix(c(0,0,2:0), 3,5))
# 3 x 5 sparse Matrix of class "dgCMatrix"
#               
# [1,] . 1 . . 2
# [2,] . . 2 . 1
# [3,] 2 . 1 . . 

(m2 <- list("Gene Expression" = m, 
            "Gene Expression" = m))
# $`Gene Expression`
# 3 x 5 sparse Matrix of class "dgCMatrix"
#               
# [1,] . 1 . . 2
# [2,] . . 2 . 1
# [3,] 2 . 1 . .
# 
# $`Gene Expression`
# 3 x 5 sparse Matrix of class "dgCMatrix"
#               
# [1,] . 1 . . 2
# [2,] . . 2 . 1
# [3,] 2 . 1 . .

attributes(m2)
# $names
# [1] "Gene Expression" "Gene Expression"

attributes(m2)[1] <- list(names = paste0("Gene Expression_",
                                         1:length(m2)))
# $names
# [1] "Gene Expression_1" "Gene Expression_2"

It looks like you're fairly new to SO; welcome to the community! If you want great answers quickly, it's best to make your question reproducible. This includes sample data like the output from dput(head(dataObject))) and any libraries you are using. Check it out: making R reproducible questions.

Kat
  • 15,669
  • 3
  • 18
  • 51