scRNA---Day7(scater)

跟着官网说明学习scater包

introduction
scater contains tools to help with the analysis of single-cell transcriptomic data, focusing on low-level steps such as quality control, normalization and visualization. It is based on the SingleCellExperiment class (from the SingleCellExperiment package), and thus is interoperable with many other Bioconductor packages such as scran, batchelor and iSEE.

setting up the data:
  1. generating a SingleCellExperiment obeject
  2. read.table() = fread()
  3. readSparseCounts()
quality control
  1. QC and filtering of cells---cell level QC
  2. QC and filtering of features (genes)---feature level QC
  3. QC of experimental variables---Variable-level QC
rm(list = ls()) 
Sys.setenv(R_MAX_NUM_DLLS=999)
## 首先载入文章的数据
load(file='../input.Rdata')
counts=a
counts[1:4,1:4];dim(counts)
library(stringr) 
suppressMessages(library(scater))
meta=df
head(meta) 
options(warn=-1) # turn off warning message globally

# 创建 scater 要求的对象
example_sce <- SingleCellExperiment(
  assays = list(counts = as.matrix(counts)), 
  colData = meta
)
example_sce
counts(example_sce)
class(counts(example_sce))
str(counts(example_sce))
example_sce$whee <- sample(LETTERS, ncol(example_sce), replace=TRUE)
colData(example_sce)
rowData(example_sce)$stuff <- runif(nrow(example_sce))
rowData(example_sce)
### 只有运行了下面的函数后才有各式各样的过滤指标,质量控制
genes=rownames(rowData(example_sce))
genes[grepl('^MT-',genes)]
genes[grepl('^ERCC-',genes)]



#QC
#Cell-level QC
###per.cell <- perCellQCMetrics(example_sce, 
                             ###subsets=list(Mito=grep("mt-", rownames(example_sce))))
###summary(per.cell$sum)
###本数据没有线粒体
per.cell <- perCellQCMetrics(example_sce, 
                             subsets=list(ERCC=grep("ERCC", rownames(example_sce))))
colnames(per.cell)
if(T){colnames(per.cell)#运行结果
  c([1] "sum"                   "detected"              "percent_top_50"       
  [4] "percent_top_100"       "percent_top_200"       "percent_top_500"      
  [7] "subsets_ERCC_sum"      "subsets_ERCC_detected" "subsets_ERCC_percent" 
  [10] "total") sum:total number of counts for the cell (i.e., the library size).
  detected: the number of features for the cell that have counts above the detection limit 
  (default of zero).
  subsets_X_percent: percentage of all counts that come from the feature control set named X.
  }

summary(per.cell$sum)
colData(example_sce) <- cbind(colData(example_sce), per.cell)
colData(example_sce)
plotColData(example_sce, x = "sum", y="detected", colour_by="g") ###'g'可换成metadata中的其他变量
plotColData(example_sce, x = "sum", y="subsets_ERCC_percent", 
            other_fields="g") + facet_wrap(~g)#不同组中的内源性基因及ERCC(本数据中无线粒体),faceted by group
##Identifying low-quality cells
###根据counts数及detected数进行筛选
if (F){
  keep.total <- example_sce$sum > 1e5 
###(100000可以调整,该条件的意思是一个样本(细胞)中所有表达基因的counts数需大于100000)
keep.n <- example_sce$detected > 500 ###一个样本(细胞)中至少检测到有500个基因表达
filtered <- example_sce[,keep.total & keep.n]
dim(filtered)
}
###isOutlier()函数根据公式(基于MAD)筛选
if (F){
  keep.total <- isOutlier(per.cell$sum, type="lower", log=TRUE)
filtered.mad <- example_sce[,keep.total]
dim(filtered.mad)
}
### quickPerCellQC()函数(基于对照/排除筛选-ERCC/MT-)
if (T){
  qc.stats <- quickPerCellQC(per.cell, percent_subsets="subsets_ERCC_percent")
colSums(as.matrix(qc.stats))
filtered.qc <- example_sce[,!qc.stats$discard]
dim(filtered.qc)
}

#Feature-level QC
##mean: the mean count of the gene/feature across all cells.
##detected: the percentage of cells with non-zero counts for each gene.
##subsets_Y_ratio: ratio of mean counts between the cell control set named Y and all cells.
raw.example = example_sce
example_sce = filtered.qc
per.feat <- perFeatureQCMetrics(example_sce)
summary(per.feat$mean)
summary(per.feat$detected)
###calculateAverage()函数基于文库大小修改基因表达量
ave <- calculateAverage(example_sce)
summary(ave)
###the number of cells expressing a gene
summary(nexprs(example_sce, byrow=TRUE))
##寻找高表达基因(默认展示50个)
plotHighestExprs(example_sce, exprs_values = "counts")
##删除过滤不表达基因
keep_feature <- nexprs(example_sce, byrow=TRUE) > 0
example_sce <- example_sce[keep_feature,]
dim(example_sce)

#Variable-level QC
###which experimental factors are contributing most to the variance in expression
###to diagnose batch effects or to quickly verify that a treatment has an effect.
example_sce <- logNormCounts(example_sce) 
assayNames(example_sce)
vars <- getVarianceExplained(example_sce, 
                             variables=c("g", "plate", "n_g"))
head(vars)
plotExplanatoryVariables(vars)

#Computing expression values
##Normalization for library size differences
###log2-transformed normalized expression values
if (T){
example_sce <- logNormCounts(raw.example)
assayNames(example_sce)
}
libsize = librarySizeFactors(example_sce)
length(libsize )
summary(librarySizeFactors(example_sce))
###calculate counts-per-million
if (T){
  cpm(example_sce) <- calculateCPM(raw.example)
  cpm(example_sce) <- calculateTPM(raw.example)
  cpm(example_sce) <- calculateFPKM(raw.example)
}

##Aggregation across groups or clusters
agg_sce <- aggregateAcrossCells(example_sce, ids=example_sce$g)
head(assay(agg_sce))
#ass = assay(agg_sce)
colData(agg_sce)[,c("ids", "ncells")]
###sum across multiple factors
#agg_sce.mul <- aggregateAcrossCells(example_sce, 
                                ids=colData(example_sce)[,c("g", "plate")])
#head(assay(agg_sce))
#colData(agg_sce)[,c("g", "plate", "ncells")]本数据无法完成多因素聚集
#agg_feat <- sumCountsAcrossFeatures(example_sce,
                                    #ids=list(GeneSet1=1:10, GeneSet2=11:50, GeneSet3=1:100),
                                    #average=TRUE, exprs_values="logcounts")
#agg_feat[,1:10]

#Visualizing expression values
plotExpression(example_sce, rownames(example_sce)[1:6], x = "g",exprs_values="logcounts")
plotExpression(example_sce, rownames(example_sce)[1:6],
               x = rownames(example_sce)[10])
plotExpression(example_sce, rownames(example_sce)[1:6],
               x = "g", colour_by="plate")

到可视化及降维那里走不下去了,感觉对应不上示例数据集-!-


几张质控的图

50Rplot.png
ERCC-plot.png
group-plot.png

vars-Rplot.png

str()函数:

即structure,紧凑的显示对象内部结构,即对象里有什么内容

metadata:

即元数据,关于数据的数据或者叫做用来描述数据的数据或者叫做信息的信息;
元数据可以为数据说明其元素或属性(名称、大小、数据类型等等),或其结构(长度、字段、数据列),或其相关数据

sample()函数:

即随机抽样,随机抽样是为了保证各组之间均衡性的一个很重要的方法
x=1:1000
sample(x=x,size=20,replace = T) 范围:1-1000 抽样次数:20 replace=T 有放回的抽样

runif()函数:

生成均匀分布的随机数
runif(n,min=0,max=1) n 生成的随机数数量,min 均匀分布的下限,max 均匀分布的上限;若省略参数min、max,则默认生成[0,1]上的均匀分布随机数

rnorm()函数

生成正态分布随机数
rnorm(n,mean=0,sd=1)n 生成的随机数数量 mean 正态分布的均值 默认为0 sd是正态分布的标准差默认时为1
代码修改

rm(list = ls()) 
Sys.setenv(R_MAX_NUM_DLLS=999)
## 首先载入文章的数据
load(file='../input.Rdata')
counts=a
counts[1:4,1:4];dim(counts)
library(stringr) 
suppressMessages(library(scater))
meta=df
head(meta) 
options(warn=-1) # turn off warning message globally

# 创建 scater 要求的对象
example_sce <- SingleCellExperiment(
  assays = list(counts = as.matrix(counts)), 
  colData = meta
)
example_sce
counts(example_sce)
class(counts(example_sce))
str(counts(example_sce))
### 只有运行了下面的函数后才有各式各样的过滤指标,质量控制
genes=rownames(rowData(example_sce))
genes[grepl('^MT-',genes)]
genes[grepl('^ERCC-',genes)]#24490 92
example_sce$whee <- sample(LETTERS, ncol(example_sce), replace=TRUE)
colData(example_sce)
rowData(example_sce)$stuff <- runif(nrow(example_sce))
rowData(example_sce)$featureType <- c(rep("endogenous", 24490), rep("ERCC",92))
rowData(example_sce)

#QC
#Cell-level QC
###per.cell <- perCellQCMetrics(example_sce, 
                             ###subsets=list(Mito=grep("mt-", rownames(example_sce))))
###summary(per.cell$sum)
###本数据没有线粒体
per.cell <- perCellQCMetrics(example_sce, 
                             subsets=list(ERCC=grep("ERCC", rownames(example_sce))))
colnames(per.cell)
if(T){colnames(per.cell)#运行结果
  #c([1] "sum"                   "detected"              "percent_top_50"       
  #[4] "percent_top_100"       "percent_top_200"       "percent_top_500"      
  #[7] "subsets_ERCC_sum"      "subsets_ERCC_detected" "subsets_ERCC_percent" 
  #[10] "total") 
  #sum:total number of counts for the cell (i.e., the library size).
  #detected: the number of features for the cell that have counts above the detection limit 
  #default of zero).
  #subsets_X_percent: percentage of all counts that come from the feature control set named X.
  }

summary(per.cell$sum)
colData(example_sce) <- cbind(colData(example_sce), per.cell)
colData(example_sce)
plotColData(example_sce, x = "sum", y="detected", colour_by="g") ###'g'可换成metadata中的其他变量
plotColData(example_sce, x = "sum", y="subsets_ERCC_percent", 
            other_fields="g") + facet_wrap(~g)#不同组中的内源性基因及ERCC(本数据中无线粒体),faceted by group
##Identifying low-quality cells
###根据counts数及detected数进行筛选
if (F){
  keep.total <- example_sce$sum > 1e5 
###(100000可以调整,该条件的意思是一个样本(细胞)中所有表达基因的counts数需大于100000)
keep.n <- example_sce$detected > 500 ###一个样本(细胞)中至少检测到有500个基因表达
filtered <- example_sce[,keep.total & keep.n]
dim(filtered)
}
###isOutlier()函数根据公式(基于MAD)筛选
if (F){
  keep.total <- isOutlier(per.cell$sum, type="lower", log=TRUE)
filtered.mad <- example_sce[,keep.total]
dim(filtered.mad)
}
### quickPerCellQC()函数(基于对照/排除筛选-ERCC/MT-)
if (T){
  qc.stats <- quickPerCellQC(per.cell, percent_subsets="subsets_ERCC_percent")
colSums(as.matrix(qc.stats))
filtered.qc <- example_sce[,!qc.stats$discard]
dim(filtered.qc)
}

#Feature-level QC
##mean: the mean count of the gene/feature across all cells.
##detected: the percentage of cells with non-zero counts for each gene.
##subsets_Y_ratio: ratio of mean counts between the cell control set named Y and all cells.
###raw.example = example_sce
###example_sce = filtered.qc
tmp = as.data.frame(rowData(filtered.qc))
colnames(tmp)
head(tmp)
`per.feat <- perFeatureQCMetrics(example_sce, subsets=list(Empty=1:10))`#官网格式数据
per.feat <- perFeatureQCMetrics(filtered.qc)
summary(per.feat$mean)
summary(per.feat$detected)
###calculateAverage()函数基于文库大小修改基因表达量
ave <- calculateAverage(filtered.qc)
summary(ave)
###the number of cells expressing a gene
summary(nexprs(filtered.qc, byrow=TRUE))
##寻找高表达基因(默认展示50个)
plotHighestExprs(example_sce, exprs_values = "counts")
##删除过滤不表达基因
keep_feature <- nexprs(filtered.qc, byrow=TRUE) > 0
filter_sce <- filtered.qc[keep_feature,]
dim(filter_sce)

if (T){
  ###使用由函数得到的per.feat自己写代码完成过滤
  filtered.qc[per.feat$detected != 0];filtered.qc[per.feat$mean != 0]
  x1 = as.data.frame((rowData(filtered.qc[per.feat$detected != 0][255][1])))
  x2 = as.data.frame((rowData(filtered.qc[per.feat$mean != 0][255][1])))
  ###验证选取detected与选取mean结果一致
}
#Variable-level QC
###which experimental factors are contributing most to the variance in expression
###to diagnose batch effects or to quickly verify that a treatment has an effect.
filter_sce <- logNormCounts(filter_sce) 
assayNames(filter_sce)
vars <- getVarianceExplained(filter_sce, 
                             variables=c("g", "plate"))
head(vars)
plotExplanatoryVariables(vars)

#Computing expression values
##Normalization for library size differences
###log2-transformed normalized expression values
if (T){
example_sce <- logNormCounts(raw.example)
assayNames(example_sce)
}
libsize = librarySizeFactors(example_sce)
length(libsize )
summary(librarySizeFactors(example_sce))
###calculate counts-per-million
if (T){
  cpm(example_sce) <- calculateCPM(raw.example)
  cpm(example_sce) <- calculateTPM(raw.example)
  cpm(example_sce) <- calculateFPKM(raw.example)
}

##Aggregation across groups or clusters
agg_sce <- aggregateAcrossCells(example_sce, ids=example_sce$g)
head(assay(agg_sce))
#ass = assay(agg_sce)
colData(agg_sce)[,c("ids", "ncells")]
###sum across multiple factors
#agg_sce.mul <- aggregateAcrossCells(example_sce, 
                                #ids=colData(example_sce)[,c("g", "plate")])
#head(assay(agg_sce))
#colData(agg_sce)[,c("g", "plate", "ncells")]本数据无法完成多因素聚集
#agg_feat <- sumCountsAcrossFeatures(example_sce,
                                    #ids=list(GeneSet1=1:10, GeneSet2=11:50, GeneSet3=1:100),
                                    #average=TRUE, exprs_values="logcounts")
#agg_feat[,1:10]

#Visualizing expression values
plotExpression(example_sce, rownames(example_sce)[1:6], x = "g",exprs_values="logcounts")
plotExpression(example_sce, rownames(example_sce)[1:6],
               x = rownames(example_sce)[10])
plotExpression(example_sce, rownames(example_sce)[1:6],
               x = "g", colour_by="plate")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,616评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,020评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,078评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,040评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,154评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,265评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,298评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,072评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,491评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,795评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,970评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,654评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,272评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,985评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,223评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,815评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,852评论 2 351