跟着官网说明学习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:
- generating a SingleCellExperiment obeject
read.table() = fread()
- readSparseCounts()
quality control
- QC and filtering of cells---cell level QC
- QC and filtering of features (genes)---feature level QC
- 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")
到可视化及降维那里走不下去了,感觉对应不上示例数据集-!-
几张质控的图
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")