如何重塑数据框然后将其转换为 dgCMatrix?

How to reshape and then convert a data frame into dgCMatrix?

我有一个如下所示的数据框(行名是“1”、“2”、“3”...)。由于每列中都有非唯一条目,因此我无法将它们中的任何一个指定为行名。

gene cell count
a    c1    1
a    c2    1
a    c3    4
b    c1    3
b    c2    1
b    c3    1
f    c1    3
d    c8    9
e    c11   1

每个基因在每个单元格中测量(意味着它们在计数列中有一个值)但未显示零计数(例如基因 "a" 在单元格 c8 和 c11 中的计数为零,因此不显示).

现在我想 reshape/convert 数据帧进入 dgCMatrix 具有以下安排

(基因作为行名,细胞作为列名,计数值作为数据点)

   c1  c2  c3  c8  c11 
a  1   1   4   .    .
c  3   1   1   .    . 

其中“.”对应于零计数。

我尝试了 reshape、reshape2、as.matrix,但没有成功。

您转换为长格式并首先将基因列设置为行名:

library(Matrix)
library(dplyr)
library(tidyr)

mat <- df %>% pivot_wider(id_cols = gene,values_from = count,names_from = cell,
values_fill = list(count=0)) %>% tibble::column_to_rownames("gene")

然后到稀疏矩阵:

mat = Matrix(as.matrix(mat),sparse=TRUE)

    5 x 5 sparse Matrix of class "dgCMatrix"
  c1 c2 c3 c8 c11
a  1  1  4  .   .
b  3  1  1  .   .
f  3  .  .  .   .
d  .  .  .  9   .
e  .  .  .  .   1