基于R语言Rcpp包解决单细胞数据过大无法转换为Matrix的问题(附AUCell的简单使用)

引言:由于单细胞数据过于庞大,在读入时我们可以创建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去计算基因集活性吧!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kevin丶大牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值