我有一个如下所示的数据框(行名称为“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 /转换为 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
关于r - 如何 reshape 数据帧并将其转换为 dgCMatrix?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60189902/