r-使用lapply迭代更改对象列表中向量属性的值



我有一个dgCMatrix对象列表,我想在每个对象中编辑一个特定的向量,使其具有迭代后缀,每个对象都有一个新后缀。我的对象如下所示:dgCMatrix列表中的对象

我想添加后缀的矢量是第二个dim名称矢量,即单元格条形码。

我一直在尝试这样做:

#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)
})

但是,当我真的想更改已经存在的my_sparse_matrices对象中的每个向量时,这似乎会将更改后的向量保存到my_sparse _matrices。

我这样做是因为我试图将所有这些单细胞表达式矩阵聚合到一个rLiger对象中,该对象需要一个稀疏矩阵列表。然而,矩阵之间的单元格不能具有相同的名称,因此需要为每个单元格提供唯一的后缀。有人能帮我做些什么吗?我对使用lapply还比较陌生。

这里并不需要循环或矢量化。如果您要检查列表的属性:

attributes(my_sparse_matrices)

您将看到这些矩阵的所有名称的列表。

更改名称:

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

由于你的问题无法重现,我制作了一些数据来验证这一点。

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"

看起来你对SO还相当陌生;欢迎加入社区!如果你想快速得到好的答案,最好能让你的问题重现。这包括示例数据,如dput(head(dataObject)))和您正在使用的任何库的输出。看看:制作R可重复的问题。

相关内容