在R情况中,用的非常广泛的函数就是as.matrix(),但是,当转化的希罕矩阵对象非常巨大的时间,比方细胞数目非常多的单细胞数据,R就会报如下雷同的错误:
Error in asMethod(object) : Cholmod error 'problem too large' at file ../Core/cholmod_dense.c缘故原由&办理
这是由于as.matrix这个函数自己不支持大要量的希罕矩阵转换为稠密矩阵(也就是我们常规的矩阵),但假如采取用高级语言(比方R或python)循环填进去的方法的话,极其淹灭资源,以是可以选择直接修改该函数的底层C++语言,来办理这个题目:
library(Rcpp)Rcpp::sourceCpp(code='#include <Rcpp.h>using namespace Rcpp;// [[Rcpp::export]]IntegerMatrix asMatrix(NumericVector rp, NumericVector cp, NumericVector z, int nrows, int ncols){ int k = z.size() ; IntegerMatrix mat(nrows, ncols); for (int i = 0; i < k; i++){ mat(rp,cp) = z; } return mat;}' )as_matrix <- function(mat){ row_pos <- mat@i col_pos <- findInterval(seq(mat@x)-1,mat@p[-1]) tmp <- asMatrix(rp = row_pos, cp = col_pos, z = mat@x, nrows = mat@Dim[1], ncols = mat@Dim[2]) row.names(tmp) <- mat@Dimnames[[1]] colnames(tmp) <- mat@Dimnames[[2]] return(tmp)}as_matirx() #接下来调用即可PS,假如数据是浮点型必要把上述的IntegerMatrix替换为NumericMatrix,否则会强制转化为整型的矩阵。
构建希罕矩阵