引言:由于单细胞数据过于庞大,在读入时我们可以创建Seurat对象。但为了解决一些问题,我们不得不调用一些以Matrix格式为输入的R包,如我遇到的AUCell无法将其表达谱数据转换读入。分析之后,了解到根本原因就是R语言无法使用对庞大的数据转换为Matrix,即R语言自带的as.matrix()无效。那么如何进行转换呢?
解决办法:调用Rcpp包改写为C++代码,进行运行,再返回表达谱数据。
示例:如上述,我需要AUCell包进行分析。所以这里主要使用前提如下:
(1)R包:AUCell和Rcpp
(2)数据:单细胞数据(这里使用GSEXXX代之)
library(AUCell)
library(Rcpp)
library(dplyr)
####Matrix数据转换####
#注:如果数据为浮点型,则IntegerMatrix改为NumericMatrix
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[i],cp[i]) = z[i];
}
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)
}
cell_Type <- GSEXXX@meta.data$pre_cellType
exprMat <- GetAssayData(object = GSEXXX, slot = "counts") %>% as_matrix(.)
####AUCell基因集活性分析####
cells_rankings <- AUCell_buildRankings(exprMat)#基因排序
cells_assignment <- AUCell_exploreThresholds(cells_AUC,plotHist=TRUE,nCores=1,assign=TRUE)#挑选阈值
cells_AUC <- AUCell_calcAUC(h.sets, cells_rankings, aucMaxRank=nrow(cells_rankings)*0.05)#计算AUC值
结果:上述代码中,首先我们通过GetAssayDATA()函数获取表达谱数据,然后使用由Rcpp包写的as_matrix()方法,就可以将其转换为Matrix数据格式,然后轻轻松松使用AUCell去计算基因集活性吧!