Contents

1 Introduction

The goal of this package is to encourage the user to try many different clustering algorithms in one package structure, and we provide strategies for creating a unified clustering from these many clustering resutls. We give tools for running many different clusterings and choices of parameters. We also provide visualization to compare many different clusterings and algorithm tools to find common shared clustering patterns. We implement common post-processing steps unrelated to the specific clustering algorithm (e.g. subsampling the data for stability, finding cluster-specific markers via differential expression, etc).

The other main goal of this package is to implement strategies that we have developed in the RSEC algorithm (Resampling-based Sequential Ensemble Clustering) for finding a single robust clustering based on the many clusterings that the user might create by perturbing various parameters of a clustering algorithm. There are several steps to these strategies that we call our standard clustering workflow. The RSEC function is our preferred realization of this workflow that depends on subsampling and other ensemble methods to provide robust clusterings, particularly for single-cell sequencing experiments and other large mRNA-Seq experiments.

We also provide a class ClusterExperiment that inherits from SummarizedExperiment to store the many clusterings and related information, and a class ClusterFunction that encodes a clustering routine so that users can create customized clustering routines in a standardized way that can interact with our clustering workflow algorithms.

All of our methods also have a barebones version that allows input of matrices and greater control. This comes at the expense of the user having to manage and keep track of the clusters, input data, transformation of the data, etc. We do not discuss these barebone versions in this tutorial. Instead, we focus on using the SummarizedExperiment object as the input and working with the resulting ClusterExperiment object. See the help pages of each method for more on how to allow for matrix input.

Although this package was developed with (single-cell) RNA-seq data in mind, its use is not limited to RNA-seq or even to gene expression data. Any dataset characterized by high dimensionality could benefit from the methods implemented here.

1.1 The RSEC clustering workflow

The package encodes many common practices that are shared across clustering algorithms, like subsampling the data, computing silhouette width, sequential clustering procedures, and so forth. It also provides novel strategies that we developed as part of the RSEC algorithm (Resampling-based Sequential Ensemble Clustering) .

As mentioned above, RSEC is a specific algorithm for creating a clustering that follows these basic steps:

  • Implement many different clusterings using different choices of parameters using the function clusterMany. This results in a large collection of clusterings, where each clustering is based on different parameters.
  • Find a unifying clustering across these many clusterings using the combineMany function.
  • Determine whether some clusters should be merged together into larger clusters. This involves two steps:
    • Find a hierarchical clustering of the clusters found by combineMany using makeDendrogram
    • Merge together clusters of this hierarchy based on the percentage of differential expression, using mergeClusters.

The basic premise of RSEC is to find small, robust clusters of samples, and then merge them into larger clusters as relevant. We find that many algorithmic methods for choosing the appropriate number of clusters for methods err on the side of too few clusters. However, we find in practice that we tend to prefer to err on finding many clusters and then merging them based on examining the data.

The RSEC function is a wrapper around these steps that makes many specific choices in this basic workflow. However, many steps of this workflow are useful for users separately and for this reason, the clusterExperiment package generalizes this workflow so that the user can follow this workflow with their own choices. We call this generalization the clustering workflow, as oppose to the specific choices set in RSEC.

Users can also run or add their own clusters to this workflow at different stages. Additional functionality for creating a single clustering is also available in the clusterSingle function, and the user should see the documentation in the help page of that function.

2 Quickstart

In this section we give a quick introduction to the package and the RSEC wrapper which creates the clustering. We will also demonstrate how to find features (biomarkers) that go along with the clusters.

2.1 The Data

We will make use of a single cell RNA sequencing experiment made available in the scRNAseq package.

set.seed(14456) ## for reproducibility, just in case
library(scRNAseq)
data("fluidigm")

We will use the fluidigm dataset (see help("fluidigm")). This dataset is stored as a SummarizedExperiment object. We can access the data with assay and metadata on the samples with colData.

assay(fluidigm)[1:5,1:10]
##          SRR1275356 SRR1274090 SRR1275251 SRR1275287 SRR1275364 SRR1275269
## A1BG              0          0          0          0          0          0
## A1BG-AS1          0          0          0          0          0          0
## A1CF              0          0          0          0          0          0
## A2M               0          0          0         31          0         46
## A2M-AS1           0          0          0          0          0          0
##          SRR1275263 SRR1275242 SRR1275338 SRR1274117
## A1BG              0          0          0          0
## A1BG-AS1          0          0          0          0
## A1CF              0          0          0          0
## A2M               0          0          0         29
## A2M-AS1           0          0          0        133
colData(fluidigm)[,1:5]
## DataFrame with 130 rows and 5 columns
##               NREADS  NALIGNED    RALIGN TOTAL_DUP    PRIMER
##            <numeric> <numeric> <numeric> <numeric> <numeric>
## SRR1275356  10554900   7555880   71.5862   58.4931 0.0217638
## SRR1274090    196162    182494   93.0323   14.5122 0.0366826
## SRR1275251   8524470   5858130   68.7213   65.0428 0.0351827
## SRR1275287   7229920   5891540   81.4884   49.7609 0.0208685
## SRR1275364   5403640   4482910   82.9609   66.5788 0.0298284
## ...              ...       ...       ...       ...       ...
## SRR1275259   5949930   4181040   70.2705   52.5975 0.0205253
## SRR1275253  10319900   7458710   72.2747   54.9637 0.0205342
## SRR1275285   5300270   4276650   80.6873   41.6394 0.0227383
## SRR1275366   7701320   6373600     82.76   68.9431 0.0266275
## SRR1275261  13425000   9554960   71.1727   62.0001 0.0200522
NCOL(fluidigm) #number of samples
## [1] 130

2.2 Filtering and normalization

While there are 130 samples, there are only 65 cells, because each cell is sequenced twice at different sequencing depth. We will limit the analysis to the samples corresponding to high sequencing depth.

se <- fluidigm[,colData(fluidigm)[,"Coverage_Type"]=="High"]

We also filter out lowly expressed genes: we retain only those genes with at least 10 reads in at least 10 cells.

wh_zero <- which(rowSums(assay(se))==0)
pass_filter <- apply(assay(se), 1, function(x) length(x[x >= 10]) >= 10)
se <- se[pass_filter,]
dim(se)
## [1] 7069   65

This removed 19186 genes out of 26255. We now have 7069 genes (or features) remaining. Notice that it is important to remove genes with zero counts in all samples (we had 9673 genes which were zero in all samples here). Otherwise, PCA dimensionality reductions and other implementations may have a problem.

Normalization is an important step in any RNA-seq data analysis and many different normalization methods have been proposed in the literature. Comparing normalization methods or finding the best performing normalization in this dataset is outside of the scope of this vignette. Instead, we will use a simple quantile normalization that will at least make our clustering reflect the biology rather than the difference in sequencing depth among the different samples.

fq <- round(limma::normalizeQuantiles(assay(se)))
assays(se) <- list(normalized_counts=fq)

As one last step, we are going to change the name of the columns “Cluster1” and “Cluster2” that some in the dataset and refer to published clustering results from the paper; we will use the terms “Published1” and “Published2” to better distinguish them in later plots from other clustering we will do.

wh<-which(colnames(colData(se)) %in% c("Cluster1","Cluster2"))
colnames(colData(se))[wh]<-c("Published1","Published2")

2.3 Clustering with RSEC

We will now run RSEC to find clusters of the cells using the default settings. We set isCount=TRUE to indicate that the data in se is count data, so that the log-transform and other count methods should be applied. We also choose the number of cores on which we want to run the operation in parallel via the parameter ncores. This is a relatively small number of samples, compared to most single-cell sequencing experiments, so we choose cluster on the top 10 PCAs of the data by setting reduceMethod="PCA" and nReducedDims=10 (the default is 50). Finally, we set the minimum cluster size in our ensemble clustering to be 3 cells (combineMinSize=3). We do this not for biological reasons, but for instructional purposes to allow us to get a larger number of clusters.

Because this procedure is slightly computationally intensive, depending on the user’s machine, we have set this code to not run so that the vignette will compile quickly upon installation. However, it doesn’t take very long (roughly 1-2 minutes) so we recommend users try it themselves by running the following code (or setting eval=TRUE in the .Rmd file) with the ncores option appropriately chosen for their machine.

library(clusterExperiment)
system.time(rsecFluidigm<-RSEC(se, isCount = TRUE, 
    reduceMethod="PCA", nReducedDims=10,combineMinSize=3,
    ncores=1, random.seed=176201))

Instead we have saved the results from this call as a data object in the package and will use the following code to load it into the vignette:

#don't call this routine if you ran the above code.
#it will overwrite the rsecFluidigm you made
library(clusterExperiment)
data("rsecFluidigm")

2.3.1 The output

We can look at the object that was created.

rsecFluidigm
## class: ClusterExperiment 
## dim: 7069 65 
## reducedDimNames: no reduced dims stored 
## filterStats: no valid filtering stats stored 
## -----------
## Primary cluster type: mergeClusters 
## Primary cluster label: mergeClusters 
## Table of clusters (of primary clustering):
## -1 m1 m2 m3 m4 m5 m6 
## 13 24 15  4  3  3  3 
## Total number of clusterings: 38 
## Dendrogram run on 'combineMany' (cluster index: 2)
## -----------
## Workflow progress:
## clusterMany run? Yes 
## combineMany run? Yes 
## makeDendrogram run? Yes 
## mergeClusters run? Yes

The print out tells us about the clustering(s) that were created (namely 38 clusterings) and which steps of the workflow have been called (all of them have because we used the wrapper RSEC that does the whole thing). Recall from our brief description above that RSEC clusters the data many times using different parameters before finding an consensus clustering. All of these intermediate clusterings are saved. Each of these intermediate clusterings used subsampling of the data and sequential clustering of the data to find the clustering, while the different clusterings represent the different parameters that were adjusted.

We can see that rsecFluidigm has a built in (S4) class called a ClusterExperiment object. This is a class built for this package and explained in the section on ClusterExperiment Objects. In the object rsecFluidigm the clusterings are stored along with corresponding information for each clustering. Furthermore, all of the information in the original SummarizedExperiment is retained. The print out also tells us information about the “primaryCluster” of rsecFluidigm. Each ClusterExperiment object has a “primaryCluster”, which is the default cluster that the many functions will use unless specified by the user. We are told that the “primaryCluster” for rsecFluidigm is has the label “mergeClusters” – which is the defaul label given to the last cluster of the RSEC function because the last call of the RSEC function is to mergeClusters.

There are many accessor functions that help you get at the information in a ClusterExperiment object and some of the most relevant are described in the section on ClusterExperiment Objects. (ClusterExperiment objects are S4 objects, and are not lists).

For right now we will only mention the most basic such function that retrieves the actual cluster assignments. The final clustering created by RSEC is saved as the primary clustering of the object.

head(primaryCluster(rsecFluidigm),20)
##  [1] -1 -1  1  1 -1 -1 -1  2  2  2  1  1 -1  1  3  4 -1  2  3 -1

The clusters are encoded by consecutive integers. Notice that some of the samples are assigned the value of -1. -1 is the value assigned in this package for samples that are not assigned to any cluster. Why certain samples are not clustered depends on the underlying choices of the clustering routine and we won’t get into here until we learn a bit more about RSEC. Another special value is -2 discussed in the section on ClusterExperiment objects

This final result of RSEC is the result of running many clusterings and finding the ensembl consensus between them. All of the these intermediate clusterings are saved in rsecFluidigm object. They can be accessed by the clusterMatrix function, that returns a matrix where the columns are the different clusterings and the rows are samples. We show a subset of this matrix here:

head(clusterMatrix(rsecFluidigm)[,1:4])
##            mergeClusters combineMany k0=4,alpha=0.1 k0=5,alpha=0.1
## SRR1275356            -1          -1             -1             -1
## SRR1275251            -1          -1             -1             -1
## SRR1275287             1           1              1              1
## SRR1275364             1           2             -1             -1
## SRR1275269            -1          -1             -1             -1
## SRR1275263            -1          -1             -1             -1

The “mergeClusters” clustering is the final clustering from RSEC and matches the primary clustering that we saw above. The “combineMany” clustering is the result of the initial ensembl concensus among all of the many clusterings that were run, while “mergeClusters” is the result of merging smaller clusters together that did not show enough signs of differences between clusters. The remaining clusters are the result of changing the parameters, and a couple of such clusterings a shown in the above printout of the cluster matrix.

The column names are the clusterLabels for each clustering and can be accessed (and assigned new values!) via the clusterLabels function.

head(clusterLabels(rsecFluidigm))
## [1] "mergeClusters"  "combineMany"    "k0=4,alpha=0.1" "k0=5,alpha=0.1"
## [5] "k0=6,alpha=0.1" "k0=7,alpha=0.1"

We can see the names of more clusterings, and see that the different parameter values tried in each clustering are saved in the names of the clustering. We can also see the different parameter combinations that went into the consensus clustering by using getClusterManyParams (here only 2 different parameters).

head(getClusterManyParams(rsecFluidigm))
##                clusteringIndex k alpha
## k0=4,alpha=0.1               3 4   0.1
## k0=5,alpha=0.1               4 5   0.1
## k0=6,alpha=0.1               5 6   0.1
## k0=7,alpha=0.1               6 7   0.1
## k0=8,alpha=0.1               7 8   0.1
## k0=9,alpha=0.1               8 9   0.1

2.3.2 Visualizing the output

clusterExperiment also provides many ways to visualize the output of RSEC (or any set of clusterings run in clusterExperiment, as we’ll show below).

Visualizing many clusterings The first such useful visualization is a plot of all of the clusterings together using the plotClusters command. For this visualization, it is useful to change the amount of space on the left of the plot to allow for the labels of the clusterings, so we will reset the mar option in par. We also decrease the axisLine argument that decides the amount of space between the axis and the labels to give more space to the labels (axisLine is passed internally to the line option in axis).

defaultMar<-par("mar")
plotCMar<-c(1.1,8.1,4.1,1.1)
par(mar=plotCMar)
plotClusters(rsecFluidigm,main="Clusters from RSEC", whichClusters="workflow", sampleData=c("Biological_Condition","Published2"), axisLine=-1)

This plot shows the samples in the columns, and different clusterings on the rows. Each sample is color coded based on its clustering for that row, where the colors have been chosen to try to match up clusters across different clusterings that show large overlap. Moreover, the samples have been ordered so that each subsequent clustering (starting at the top and going down) will try to order the samples to keep the clusters together, without rearranging the clustering blocks of the previous clustering/row.

We also added a sampleData argument in our call, indicating that we also want to visualize some information about the samples saved in the colData slot (inherited from our original fluidigm object). We chose the columns “Biological_Condition” and “Published2” from colData, which correspond to the original biological condition of the experiment, and the clusters reported in the original paper, respectively. The data from sampleData (when requested) are always shown at the bottom of the plot.

Notice that some samples are white. This indicates that they have the value -1, meaning they were not clustered. In fact, for many clusterings, there is a large amount of white here. This is likely do to the fact that there are only 65 cells here, and the default parameters of RSEC are better suited for a large number of cells, such as seen in more modern single-cell sequencing experiments. The sequential clustering may be problematic for small numbers of cells.

We can use an alternative version of plotClusters called plotClustersWorkflow that will better emphasize the more final clusterings from the ensemble/concensus step and merging steps (it currently does not allow for showing the sampleData as well, however – only clustering results).

par(mar=plotCMar)
plotClustersWorkflow(rsecFluidigm)

Barplots We can examine size distribution of a single clustering with the function plotBarplot. By default, the cluster picked will be the primary cluster, which for the result of clusterMany is rather arbitrarily just the first cluster.

plotBarplot(rsecFluidigm,main="Final Clustering")

We can also pick a particular intermediate clustering, say our intial ensembl clustering before merging.

plotBarplot(rsecFluidigm,whichClusters=c("combineMany" ))

We can also compare two specific clusters with a simple barplot using plotBarplot. Here we compare the “combineMany” and the “mergeClusters” clusterings.

plotBarplot(rsecFluidigm,whichClusters=c("mergeClusters" ,"combineMany"))

Since “combineMany” is a partition of “mergeClusters”, there is perfect subsetting within the clusters of “mergeClusters”.

Co-Clustering We can also visualize the proportion of times samples were together in the individual clusterings (i.e. before the consensus clustering):

plotCoClustering(rsecFluidigm,whichClusters=c("mergeClusters","combineMany"))

Note that this is not the result from any particular subsampling (which was done repeatedly for each clustering), but the proportion of times across the clusterings we ran. The initial consensus clustering in combineMany was made based on these proportions and a particular cutoff of the required proportion of times the samples needed to be together.

Plot of Dendrogram We can visualize how the initial ensembl cluster in combineMany was clustered into a hierarchy and merged to give us the final clustering in mergeClusters:

plotDendrogram(rsecFluidigm,whichClusters=c("combineMany","mergeClusters"),plotType="colorblock",leafType="sample")

As shown in this plot, the individual clusters of the combineMany ensembl clustering were hierarchically clustered (hence the note that the dendrogram was made from the combineMany clustering), and similar sister clusters were merged if there were not enough gene differences between them.

2D plot of clusters Finally, we can plot a 2-dimensional representation of the data with PCA and color code the samples to get a sense of how the data cluster.

plotReducedDims(rsecFluidigm)

We can also look at a higher number of dimensions (or different dimensions) by changing the parameter ‘whichDims’.

plotReducedDims(rsecFluidigm,whichDims=c(1:4))

In this case we can see that higher dimensions show us a greater amount of separation between the clusters than in just 2 dimensions.

2.4 Rerunning RSEC with different parameters

In the next section, we will describe more about the options we could adjust in RSEC. As an example of a few options, we might, for example, want to change the proportion of co-clustering we required in making our combineMany clustering (which used the default of 0.7), or change the proportion of genes that must show differences in order to not merge clusters or the method of deciding. We can call RSEC again on our object rsecFluidigm and it will not redo the many individual clustering steps which are time intensive (unless we request it to rerun it by including the argument rerunClusterMany=TRUE). We demonstrate this in our next command where we change these choices in the following ways:

  • set the proportion of co-clustering required by the argument combineProportion=0.6,
  • make the merge cutoff mergeCutoff=0.01
  • decide to use a different method of estimating the proportion differential for merge by setting mergeMethod="Storey" instead of the default (“adjP”).
  • no longer adjust the minimum cluster size and use the default (combineMinSize=5).

These are the main parameters we might frequently want to tweak in RSEC.

rsecFluidigm<-RSEC(rsecFluidigm,isCount=TRUE,combineProportion=0.6,mergeMethod="JC",mergeCutoff=0.05)

Notice that we save the output over our original object. This is the standard way to work with the ClusterExperiment objects, since the package’s commands just continues to add the clusterings, without deleting anything from before. In this way, we do not duplicate the actual data in our workspace (which is often large).

We can compare the results of our changes with the whichClusters command to explicitly choose the clusterings we want to plot:

defaultMar<-par("mar")
plotCMar<-c(1.1,8.1,4.1,1.1)
par(mar=plotCMar)
plotClusters(rsecFluidigm,main="Clusters from RSEC", whichClusters=c("mergeClusters.1","combineMany.1","mergeClusters","combineMany"), sampleData=c("Biological_Condition","Published2"), axisLine=-1)

The clusterings with the .1 appended to the labels are the previous combineMany and mergeClusters clusterings from the default setting (see Rerunning to see how different versions are labeled and stored internally). We can see that we lost several clusters with these options.

In what follows, we’ll go back to the original (default) RSEC settings by rerunning RSEC (the original clusters are saved in the rsecFluidigm object, but there is useful information about the merging that is overwritten by our latest call so we will just rerun it to recreate the clustering):

rsecFluidigm<-RSEC(rsecFluidigm,combineMinSize=3)

In practice, it can be useful to interactively make choices about these parameters by rerunning each the individual steps of the workflow separately and visualizing the changes before moving to the next step, as we do below during our overview of the steps.

2.5 Finding Features related to the clusters

A common practice after determining a set of clusters is to perform differential gene expression analysis in order to find genes that show the greatest differences amongst the clusters. We would stress that this is purely an exploratory technique, and any p-values that result from this analysis are not valid, in the sense that they are likely to be inflated. This is because the same data was used to define the clusters and to perform differential expression analysis.

Since this is a common task, we provide the function getBestFeatures to perform various kinds of differential expression analysis between the clusters. A common F-statistic between groups can be chosen. However, we find that it is far more informative to do pairwise comparisons between clusters, or one cluster against all, in order to find genes that are specific to a particular cluster. An option for all of these choices is provided in the getBestFeatures function.

The getBestFeatures function uses the DE analysis provided by the limma package (Smyth 2004, Ritchie et al. (2015)). In addition, the getBestFeatures function provides an option to do use the “voom” correction in the limma package (Law et al. 2014) to account for the mean-variance relationship that is common in count data. The tests performed by getBestFeatures are specific contrasts between clustering groups; these contrasts can be retrieved without performing the tests using clusterContrasts, including in a format appropriate for the MAST algorithm.

As mentioned above, there are several types of tests that can be performed to identify features that are different between the clusters which we describe in the section entitled Finding Features related to a Clustering. Here we simply perform all pairwise tests between the clusters.

pairsAllRSEC<-getBestFeatures(rsecFluidigm,contrastType="Pairs",p.value=0.05,
                          number=nrow(rsecFluidigm))
head(pairsAllRSEC)
##   IndexInOriginal  Contrast Feature    logFC  AveExpr         t      P.Value
## 1            5745 Cl01-Cl02   STMN2 9.839919 8.440126 13.173344 4.850101e-20
## 2            3854 Cl01-Cl02   NRXN1 7.655286 5.583251 10.637778 6.938049e-16
## 3            5085 Cl01-Cl02    RTN1 7.748156 7.266948  9.802468 1.899925e-14
## 4            2325 Cl01-Cl02   GRIA2 7.920474 5.169489  9.587520 4.499016e-14
## 5            3266 Cl01-Cl02    MEG3 7.728490 5.496095  9.047550 3.984190e-13
## 6            4285 Cl01-Cl02  PLXNA2 7.636054 5.379982  9.011605 4.609957e-13
##      adj.P.Val        B
## 1 3.428536e-16 33.03996
## 2 2.452253e-12 24.65642
## 3 4.476856e-11 21.69298
## 4 7.950887e-11 20.91666
## 5 5.431297e-10 18.94485
## 6 5.431297e-10 18.81259

We can visualize only these significantly different pair-wise features with plotHeatmap by using the column “IndexInOriginal” in the result of getBestFeatures to quickly identify the genes to be used in the heatmap. Notice that the same genes can be replicated across different contrasts, so we will not always have unique genes:

length(pairsAllRSEC$Feature)==length(unique(pairsAllRSEC$Feature))
## [1] TRUE

In this case they are not unique because the same gene can be significant for different pairs tests. Hence, we will make sure we take only unique gene values so that they are not plotted multiple times in our heatmap. (This is a good practice even if in a particular case the genes are unique).

plotHeatmap(rsecFluidigm, whichClusters=c("combineMany","mergeClusters"),clusterSamplesData="dendrogramValue",
            clusterFeaturesData=unique(pairsAllRSEC[,"IndexInOriginal"]),
            main="Heatmap of features w/ significant pairwise differences",
            breaks=.99)

Notice that the samples clustered into the -1 cluster (i.e. not assigned) are clustered as an outgroup. This is a choice that is made when the dendrogram (described below). These samples can also be mixed into the dendrogram (see makeDendrogram)

We can identify the genes corresponding to the different contrasts with the plotContrastHeatmap function where the genes (rows) are organized by what contrast for which they are significant. The option nBlankLines controls the space between the groups of genes from each contrast. We also give the argument whichCluster="primary" to indicate that the contrasts were created with the primary clustering – this means that the legend will put in the names of the clusters rather than their (internal) numeric id.

plotContrastHeatmap(rsecFluidigm, signif=pairsAllRSEC,nBlankLines=40,whichCluster="primary")

3 Overview of the clustering workflow

We give an overview here of the steps used by the RSEC wrapper and more generally in the clusterExperiment package. The section The clustering workflow goes over these steps and the possible arguments in greater details.

The standard clustering workflow steps are the following:

These clustering steps are done in one function call by RSEC, described above, which is most straightforward usage. However, to understand the parameters available in RSEC it is useful to go through the steps individually. Furthermore RSEC has streamlined the workflow to concentrate on using the workflow with subsampling and sequential strategies, but going through the individual steps demonstrates how the user can make different choices.

Therefore in this section, we will go through these steps, but instead of using the parameters of RSEC that involve subsampling and are more computationally intensive, we will run through the same steps, only using just basic PAM clustering with no subsampling or sequential clustering. This is simply for the purpose of briefly understanding the intermediate steps that RSEC follows. Later sections will go through these steps in more detail and discuss the particular choices embedded in RSEC.

3.1 Step 1: Clustering with clusterMany

clusterMany lets the user quickly pick between many clustering options and run all of the clusterings in one single command. In the quick start we pick a simple set of clusterings based on varying the dimensionality reduction options. The way to designate which options to vary is to give multiple values to an argument.

Here is our call to clusterMany:

ce<-clusterMany(se, clusterFunction="pam",ks=5:10, minSizes=5,
      isCount=TRUE,reduceMethod=c("PCA","var"),nFilterDims=c(100,500,1000),
      nReducedDims=c(5,15,50),run=TRUE)

In this call to clusterMany we made the follow choices about what to vary:

  • set reduceMethod=c("PCA", "var") meaning run the clustering algorithm trying two different methods for dimensionality reduction: the top principal componetns and filtering to the top most variable genes
  • For PCA reduction, choose 5,15, and 50 principal components for the reduced data set (set nReducedDims=c(5,15,50))
  • For most variable genes reduction, we choose 100, 500, and 1000 most variable genes (set nFilterDims=c(100,500,1000))
  • For the number of clusters, vary from \(k=5,\ldots,10\) (set ks=5:10)

By giving only a single value to the relative argument, we keep the other possible options fixed, for example:

  • we used ‘pam’ for all clustering (clusterFunction="pam")
  • we set minSizes=5. This is an argument that allows the user to set a minimum required size and clusters of size less than that value will be ignored and samples assigned to them given the unassigned value of -1. The default of 1 would mean that this option is not used.

We also set isCount=TRUE to indicate that our input data are counts. This means that operations for clustering and visualizations will internally transform the data as \(log_2(x+1)\) (We could have alternatively explicitly set a transformation by giving a function to the transFun argument, for example if we wanted \(\sqrt(x)\) or \(log(x+\epsilon)\) or just identity).

We can visualize the resulting clusterings using the plotClusters command as we did for the RSEC results.

defaultMar<-par("mar")
par(mar=plotCMar)
plotClusters(ce,main="Clusters from clusterMany", whichClusters="workflow", sampleData=c("Biological_Condition","Published2"), axisLine=-1)

ce<-clusterMany(se, clusterFunction="pam",ks=5:10, minSizes=5,
      isCount=TRUE,reduceMethod=c("PCA","var"),nFilterDims=c(100,500,1000),
      nReducedDims=c(5,15,50),run=TRUE)
test<-getClusterManyParams(ce)
ord<-order(test[,"k"],test[,"nFilterDims"],test[,"nReducedDims"])
plotClusters(ce,main="Clusters from clusterMany", whichClusters=test$clusteringIndex[ord], sampleData=c("Biological_Condition","Published2"), axisLine=-1)

We can see that some clusters are fairly stable across different choices of dimensions while others can vary dramatically.

Notice that again some samples are white (i.e the value -1, meaning they were not clustered). This is from our choices to require at least 5 samples to make a cluster.

We have set whichClusters="workflow" to only plot clusters created from the workflow. Right now that’s all there are anyway, but as commands get rerun with different options, other clusterings can build up in the object (see discussion in this section about how multiple calls to workflow are stored). So setting whichClusters="workflow" means that we are only going to see our most recent calls to the workflow (so far we only have the 1 step, which is the clusterMany step). We seen already that whichClusters can be set to limit to specific clusterings or specific steps in the workflow .

We cal also give to the whichClusters an argument indices of clusters stored in the ClusterExperiment object, which can allow us to show the clusters in a different order. Here we’ll pick an order which corresponds to varying the number of dimensions, rather than k. We can find the parameters for each clustering using the getClusterManyParams

cmParams<-getClusterManyParams(ce)
head(cmParams)
##                                                     clusteringIndex
## reduceMethod=1,nReducedDims=5,nFilterDims=NA,k=5                  1
## reduceMethod=2,nReducedDims=NA,nFilterDims=100,k=5                2
## reduceMethod=1,nReducedDims=15,nFilterDims=NA,k=5                 3
## reduceMethod=1,nReducedDims=50,nFilterDims=NA,k=5                 4
## reduceMethod=2,nReducedDims=NA,nFilterDims=500,k=5                5
## reduceMethod=2,nReducedDims=NA,nFilterDims=1000,k=5               6
##                                                     reduceMethod
## reduceMethod=1,nReducedDims=5,nFilterDims=NA,k=5             PCA
## reduceMethod=2,nReducedDims=NA,nFilterDims=100,k=5           var
## reduceMethod=1,nReducedDims=15,nFilterDims=NA,k=5            PCA
## reduceMethod=1,nReducedDims=50,nFilterDims=NA,k=5            PCA
## reduceMethod=2,nReducedDims=NA,nFilterDims=500,k=5           var
## reduceMethod=2,nReducedDims=NA,nFilterDims=1000,k=5          var
##                                                     nReducedDims nFilterDims
## reduceMethod=1,nReducedDims=5,nFilterDims=NA,k=5               5          NA
## reduceMethod=2,nReducedDims=NA,nFilterDims=100,k=5            NA         100
## reduceMethod=1,nReducedDims=15,nFilterDims=NA,k=5             15          NA
## reduceMethod=1,nReducedDims=50,nFilterDims=NA,k=5             50          NA
## reduceMethod=2,nReducedDims=NA,nFilterDims=500,k=5            NA         500
## reduceMethod=2,nReducedDims=NA,nFilterDims=1000,k=5           NA        1000
##                                                     k
## reduceMethod=1,nReducedDims=5,nFilterDims=NA,k=5    5
## reduceMethod=2,nReducedDims=NA,nFilterDims=100,k=5  5
## reduceMethod=1,nReducedDims=15,nFilterDims=NA,k=5   5
## reduceMethod=1,nReducedDims=50,nFilterDims=NA,k=5   5
## reduceMethod=2,nReducedDims=NA,nFilterDims=500,k=5  5
## reduceMethod=2,nReducedDims=NA,nFilterDims=1000,k=5 5

getClusterManyParams returns the parameter values, as well as the index of the corresponding clustering (i.e. what column it is in the matrix of clusterings). It is important to note that the index will change if we add additional clusterings, as we will do later.

We will set an order with first the PCA, ordered by number of dimensions, then the Var, ordered by number of diminsions

ord<-order(cmParams[,"reduceMethod"],cmParams[,"nReducedDims"])
ind<-cmParams[ord,"clusteringIndex"]
par(mar=plotCMar)
plotClusters(ce,main="Clusters from clusterMany", whichClusters=ind, sampleData=c("Biological_Condition","Published2"), axisLine=-1)

We see that the order in which the clusters are given to plotClusters changes the plot greatly. The labels shown are those given automatically by clusterMany but can be a bit much for plotting. We choose to remove “Features” as being too wordy:

clOrig<-clusterLabels(ce)
clOrig<-gsub("Features","",clOrig)
plotClusters(ce,main="Clusters from clusterMany", whichClusters=ind, clusterLabels=clOrig[ind], sampleData=c("Biological_Condition","Published2"), axisLine=-1)

We could also permanently assign new labels in our ClusterExperiment object if we prefer, for example to be more succinct, by changing the clusterLabels of the object.

There are many different options for how to run plotClusters discussed in in the detailed section on plotClusters, but for now, this plot is good enough for a quick visualization.

3.2 Step 2: Find a consensus with combineMany

To find a consensus clustering across the many different clusterings created by clusterMany the function combineMany can be used next.

ce<-combineMany(ce,proportion=1)

The proportion argument indicates the minimum proportion of times samples should be with other samples in the cluster they are assigned to in order to be clustered together in the final assignment. Notice we get a warning that we did not specify any clusters to combine, so it is using the default – those from the clusterMany call.

If we look at the clusterMatrix of the returned ce object, we see that the new cluster from combineMany has been added to the existing clusterings. This is the basic strategy of all of these functions in this package. Any clustering function that is applied to an existing ClusterExperiment object adds the new clustering to the set of existing clusterings, so the user does not need to keep track of past clusterings and can easily compare what has changed.

We can again run plotClusters, which will now also show the result of combineMany. Instead, we’ll use plotClustersWorkflow which is nicer for looking specifically at the results of combineMany

head(clusterMatrix(ce)[,1:3])
##            combineMany reduceMethod=1,nReducedDims=5,nFilterDims=NA,k=5
## SRR1275356          -1                                                1
## SRR1275251          -1                                                2
## SRR1275287          -1                                                3
## SRR1275364          -1                                                1
## SRR1275269          -1                                                3
## SRR1275263          -1                                                2
##            reduceMethod=2,nReducedDims=NA,nFilterDims=100,k=5
## SRR1275356                                                  1
## SRR1275251                                                  2
## SRR1275287                                                  3
## SRR1275364                                                  1
## SRR1275269                                                  4
## SRR1275263                                                  1
par(mar=plotCMar)
plotClustersWorkflow(ce)

The choices of proportion=1 in combineMany is not usually a great choice, and certainly isn’t helpful here. The clustering from the default combineMany leaves most samples unassigned (white in the above plot). This is because we requires samples to be in the same cluster in every clustering in order to be assigned to a cluster together. This is quite stringent. We can vary this by setting the proportion argument to be lower. Explicit details on how combineMany makes these clusters are discussed in the section on combineMany.

So let’s label the one we found as “combineMany,1” and then create a new one. (Making or changing the label to an informative label will make it easier to keep track of this particular clustering later, particularly if we make multiple calls to the workflow).

wh<-which(clusterLabels(ce)=="combineMany")
if(length(wh)!=1) stop() else clusterLabels(ce)[wh]<-"combineMany,1"

Now we’ll rerun combineMany with proportion=0.7. This time, we will give it an informative label upfront in our call to combineMany.

ce<-combineMany(ce,proportion=0.7,clusterLabel="combineMany,0.7")
par(mar=plotCMar)
plotClustersWorkflow(ce)

We see that more clusters are detected. Those that are still not assigned a cluster from combineMany clearly vary across the clusterings as to whether the samples are clustered together or not. Varying the proportion argument will adjust whether some of the unclustered samples get added to a cluster. There is also a minSize parameter for combineMany, with the default of minSize=5. We could reduce that requirement as well and more of the unclustered samples would be grouped into a cluster. Here, we reduce it to minSize=3 (we’ll call this “combineMany,final”). We’ll also choose to show all of the different combineMany results in our call to plotClustersWorkflow:

ce<-combineMany(ce,proportion=0.7,minSize=3,clusterLabel="combineMany,final")
par(mar=plotCMar)
plotClustersWorkflow(ce,whichClusters=c("combineMany,final","combineMany,0.7","combineMany,1"),main="Min. Size=3")

As we did before for RSEC results, we can also visualize the proportion of times these clusters were together across these clusterings (this information was made and stored in the ClusterExperiment object when we called combineMany provided that proportion argument is <1):

plotCoClustering(ce)

This visualization can help in determining whether to change the value of proportion (though see combineMany for how -1 assignments affect combineMany).

3.3 Step 3: Merge clusters together with makeDendrogram and mergeClusters

Once you start varying the parameters, is not uncommon in practice to create forty or more clusterings with clusterMany. In which case the results of combineMany can often result in too many small clusters. We might wonder if they are necessary or could be logically combined together. We could change the value of proportion in our call to combineMany. But we have found that it is often after looking at the clusters, for example with a heatmap, and how different they look on individual genes that we best make this determination, rather than the proportion of times they are together in different clustering routines.

For this reason, we often find the need for an additional clustering step that merges clusters together that are not different, based on running tests of differential expression between the clusters found in combineMany. This is done by the function mergeClusters. We often display and use both sets of clusters side-by-side (that from combineMany and that from mergeClusters).

mergeClusters needs a hierarchical clustering of the clusters in order to merge clusters; it then goes progressively up that hierarchy, deciding whether two adjacent clusters can be merged. The function makeDendrogram makes such a hierarchy between clusters (by applying hclust to the medoids of the clusters). Because the results of mergeClusters are so dependent on that hierarchy, we require the user to call makeDendrogram rather than calling it automatically internally. This is because different options in makeDendrogram can affect how the clusters are hierarchically ordered, and we want to encourage the user make these choices.

As an example, here we use the 500 most variable genes to make the cluster hierarchy (note we can make different choices here than we did in the clustering).

ce<-makeDendrogram(ce,reduceMethod="var",nDims=500)
plotDendrogram(ce)

We can see that clusters 1 and 3 are most closely related, at least in the top 500 most variable genes.

We can see the relative size of the clusters by setting some options in plotDendrogram:

plotDendrogram(ce,plotType="colorblock",leafType="sample")

Notice I don’t need to make the dendrogram again, because it’s saved in ce. If we look at the summary of ce, it now has ‘makeDendrogram’ marked as ‘Yes’.

ce
## class: ClusterExperiment 
## dim: 7069 65 
## reducedDimNames: PCA 
## filterStats: var var_combineMany.final 
## -----------
## Primary cluster type: combineMany 
## Primary cluster label: combineMany,final 
## Table of clusters (of primary clustering):
## -1 c1 c2 c3 c4 c5 c6 c7 
##  6  4  8  5  9 15 14  4 
## Total number of clusterings: 39 
## Dendrogram run on 'combineMany,final' (cluster index: 1)
## -----------
## Workflow progress:
## clusterMany run? Yes 
## combineMany run? Yes 
## makeDendrogram run? Yes 
## mergeClusters run? No

Now we are ready to actually merge clusters together. We run mergeClusters that will go up this hierarchy and compare the level of differential expression (DE) in each pair. In other words, if we focus on the left side of the tree, DE tests are run, between 1 and 3, and between 6 and 8. If there is not enough DE between each of these (based on a cutoff that can be set by the user), then clusters 1 and 3 and/or 6 and 8 will be merged. And so on up the tree.

If the dataset it not too large, is can be useful to first run mergeClusters without actually saving the results so as to preview what the final clustering will be (and perhaps to help in setting the cutoff).

mergeClusters(ce,mergeMethod="adjP",plotInfo="mergeMethod")

The default is cutoff is cutoff=0.1, meaning those nodes with less than 10% of genes estimated to be differentially expressed between its two children groupings of samples are merged. This is pretty stringent, and as we see it results in no clusterings being kept.

However, the plot tells us the estimate of that proportion for each node. We can decide on a better cutoff using that information. We choose instead cutoff=0.01:

ce<-mergeClusters(ce,mergeMethod="adjP",cutoff=0.01)

par(mar=plotCMar)

Notice that now the plot has given the estimates from all of the methods (the default set by plotInfo argument), not just the adjP method. But the dotted lines of the dendrogram indicate the merging performed by the actual choices in merging made in the command (mergeMethod="adjP" and cutoff=0.01).

It can be interesting to visualize the clusterings both with the plotClustersWorkflow and the co-Proportion plot (a heatmap of the proportion of times the samples co-clustered):

plotClustersWorkflow(ce,whichClusters="workflow") #, sampleData=c("Biological_Condition","Published2")
plotCoClustering(ce,whichClusters=c("mergeClusters","combineMany"),
                 sampleData=c("Biological_Condition","Published2"),annLegend=FALSE)

Notice that mergeClusters combines clusters based on the actual values of the features, while the coClustering plot shows how often the samples clustered together. It is not uncommon that mergeClusters will merge clusters that don’t look “close” on the coClustering plot. This can be due to just the choices of the hierarchical clustering between the clusters, but can also be because the two merged clusters are not often confused for each other across the clustering algorithms, yet still don’t have strong differences on individual genes. This can be the case especially when the clustering is done on reduced PCA space, where an accumulation of small differences might consistently separate the samples (so that comparatively few clusterings are “confused” as to the samples). But because the differences are not strong on individual genes, mergeClusters combines them. These are ultimately different criteria.

Finally, we can do a heatmap visualizing this final step of clustering.

plotHeatmap(ce,clusterSamplesData="dendrogramValue",breaks=.99,
            sampleData=c("Biological_Condition", "Published1", "Published2"))

By choosing “dendrogramValue” for the clustering of the samples, we will be showing the clusters according to the hierarchical ordering of the clusters found by makeDendrogram. The argument breaks=0.99 means that the last color of the heatmap spectrum will be forced to be the top 1% of the data (rather than evenly spaced through the entire range of values). This can be helpful in making sure that rare extreme values in the upper range do not absorb too much space in the color spectrum. There are many more options for plotHeatmap, some of which are discussed in the section on plotHeatmap.

##RSEC

The above explanation follows the simple example of PAM. The original RSEC result called RSEC which calls these steps internally. Many of the options described above can be set through a call to RSEC, but some are restricted for simplicity. A detail explanation of the differences can be found in the section RSEC below. But briefly, the following RSEC command, which uses most of the arguments of RSEC:

rsecOut<-RSEC(se, reduceMethod="PCA", nReducedDims=c(50,10), k0s=4:15,
        alphas=c(0.1,0.2,0.3),betas=c(0.8,0.9), minSizes=c(1,5), clusterFunction="hierarchical01",
        combineProportion=0.7, combineMinSize=5,
        dendroReduce="mad",dendroNDims=500,
        mergeMethod="adjP",mergeCutoff=0.05,
        )

would be equivalent to the following individual steps:

ce<-clusterMany(se,ks=4:15,alphas=c(0.1,0.2,0.3),betas=c(0.8,0.9),minSizes=c(1,5),
    clusterFunction="hierarchical01", sequential=TRUE,subsample=TRUE,
         reduceMethod="PCA",nFilterDims=c(50,10))
ce<-combineMany(ce, proportion=0.7, minSize=5)
ce<-makeDendrogram(ce,reduceMethod="mad",nDims=500)
ce<-mergeClusters(ce,mergeMethod="adjP",cutoff=0.05,plot=FALSE)

Note that this mean the RSEC function always calls sequential and subsampling.

4 ClusterExperiment Objects

The ce object that we created by calling clusterMany is a ClusterExperiment object. The ClusterExperiment class is used by this package to keep the data and the clusterings together. It inherits from SummarizedExperiment, which means the data and colData and other information orginally in the fluidigm object are retained and can be accessed with the same functions as before. The ClusterExperiment object additionally stores clusterings and information about the clusterings along side the data. This helps keep everything together, and like the SummarizedExperiment object, allows for simple things like subsetting to a reduced set of subjects and being confident that the corresponding clusterings, colData, and so forth are similarly subset.

Typing the name at the control prompt results in a quick summary of the object.

ce
## class: ClusterExperiment 
## dim: 7069 65 
## reducedDimNames: PCA 
## filterStats: var var_combineMany.final 
## -----------
## Primary cluster type: mergeClusters 
## Primary cluster label: mergeClusters 
## Table of clusters (of primary clustering):
## -1 m1 m2 m3 m4 
##  6 13 17 15 14 
## Total number of clusterings: 40 
## Dendrogram run on 'combineMany,final' (cluster index: 2)
## -----------
## Workflow progress:
## clusterMany run? Yes 
## combineMany run? Yes 
## makeDendrogram run? Yes 
## mergeClusters run? Yes

This summary tells us the total number of clusterings (40), and gives some indication as to what parts of the standard workflow have been completed and stored in this object. It also gives information regarding the primaryCluster of the object. The primaryCluster is just one of the clusterings that has been chosen to be the “primary” clustering, meaning that by default various functions will turn to this clustering as the desired clustering to use. clusterMany arbitrarily sets the ‘primaryCluster’ to the first one, and each later step of the workflow sets the primary index to the most recent, but the user can set a specific clustering to be the primaryCluster with primaryClusterIndex. Often, if a function is not given a specific clustering (usually via an option whichCluster or whichClusters) the “primary” cluster is taken by default.

There are also additional commands to access the clusterings and their related information (type help("ClusterExperiment-methods") for more).

The cluster assignments are stored in the clusterMatrix slot of ce, with samples on the rows and different clusterings on the columns. We saw that we can look at the cluster matrix and the primary cluster with the commands clusterMatrix and primaryCluster

head(clusterMatrix(ce))[,1:5]
##            mergeClusters combineMany,final combineMany,0.7 combineMany,1
## SRR1275356            -1                -1              -1            -1
## SRR1275251            -1                -1              -1            -1
## SRR1275287             1                 1              -1            -1
## SRR1275364             2                 2               1            -1
## SRR1275269             1                 1              -1            -1
## SRR1275263             2                 3               2            -1
##            reduceMethod=1,nReducedDims=5,nFilterDims=NA,k=5
## SRR1275356                                                1
## SRR1275251                                                2
## SRR1275287                                                3
## SRR1275364                                                1
## SRR1275269                                                3
## SRR1275263                                                2
primaryCluster(ce)
##  [1] -1 -1  1  2  1  2  1  3  3  3  4  4  2  4  1  2  1  3  1  1  4  4  4  3
## [25] -1  3  3  3  2  4  4  2  2  1  1 -1  1  4 -1  2  1  3  3  2  3  3  2 -1
## [49]  1  4  4  4  3  4  1  2  2  3  3  2  2  2  4  2  2

Remember that we made multiple calls to combineMany: only the last such call will be shown when we use whichClusters="workflow" in our plotting (see this section for a discussion of how these repeated calls are handled.)

Negative Valued Cluster Assignments The different clusters are stored as consecutive integers, with ‘-1’ and ‘-2’ having special meaning. ‘-1’ refers to samples that were not clustered by the clustering algorithm. In our example, we removed clusters that didn’t meet specific size criterion, so they were assigned ‘-1’. ‘-2’ is for samples that were not included in the original input to the clustering. This is useful if, for example, you cluster on a subset of the samples, and then want to store this clustering with the clusterings done on all the data. You can create a vector of clusterings that give ‘-2’ to the samples not originally used and then add these clusterings to the ce object manually with addClusters.

clusterLabels gives the column names of the clusterMatrix; clusterMany has given column names based on the parameter choices, and later steps in the workflow also give a name (or allow the user to set them).

head(clusterLabels(ce),10)
##  [1] "mergeClusters"                                      
##  [2] "combineMany,final"                                  
##  [3] "combineMany,0.7"                                    
##  [4] "combineMany,1"                                      
##  [5] "reduceMethod=1,nReducedDims=5,nFilterDims=NA,k=5"   
##  [6] "reduceMethod=2,nReducedDims=NA,nFilterDims=100,k=5" 
##  [7] "reduceMethod=1,nReducedDims=15,nFilterDims=NA,k=5"  
##  [8] "reduceMethod=1,nReducedDims=50,nFilterDims=NA,k=5"  
##  [9] "reduceMethod=2,nReducedDims=NA,nFilterDims=500,k=5" 
## [10] "reduceMethod=2,nReducedDims=NA,nFilterDims=1000,k=5"

As we’ve seen, the user can also change these labels.

clusterTypes on the other hand indicates what call made the clustering. Unlike the labels, it is wise to not change the values of clusterTypes unless you are sure of what you are doing because these values are used to identify clusterings from different steps of the workflow.

head(clusterTypes(ce),10)
##  [1] "mergeClusters" "combineMany"   "combineMany.2" "combineMany.1"
##  [5] "clusterMany"   "clusterMany"   "clusterMany"   "clusterMany"  
##  [9] "clusterMany"   "clusterMany"

The information that was in the original fluidigm object has also been preserved, like colData that contains information on each sample.

colData(ce)[,1:5]
## DataFrame with 65 rows and 5 columns
##               NREADS  NALIGNED    RALIGN TOTAL_DUP    PRIMER
##            <numeric> <numeric> <numeric> <numeric> <numeric>
## SRR1275356  10554900   7555880   71.5862   58.4931 0.0217638
## SRR1275251   8524470   5858130   68.7213   65.0428 0.0351827
## SRR1275287   7229920   5891540   81.4884   49.7609 0.0208685
## SRR1275364   5403640   4482910   82.9609   66.5788 0.0298284
## SRR1275269  10729700   7806230   72.7536   50.4285 0.0204349
## ...              ...       ...       ...       ...       ...
## SRR1275259   5949930   4181040   70.2705   52.5975 0.0205253
## SRR1275253  10319900   7458710   72.2747   54.9637 0.0205342
## SRR1275285   5300270   4276650   80.6873   41.6394 0.0227383
## SRR1275366   7701320   6373600     82.76   68.9431 0.0266275
## SRR1275261  13425000   9554960   71.1727   62.0001 0.0200522

Another important slot in the ClusterExperiment object is the clusterLegend slot. This consists of a list, one element per column (or clustering) of clusterMatrix, that gives colors and names to each cluster within a clustering.

length(clusterLegend(ce))
## [1] 40
clusterLegend(ce)[1:2]
## $mergeClusters
##      clusterIds color     name
## [1,] "-1"       "white"   "-1"
## [2,] "1"        "#1F78B4" "m1"
## [3,] "2"        "#33A02C" "m2"
## [4,] "3"        "#FF7F00" "m3"
## [5,] "4"        "#6A3D9A" "m4"
## 
## $`combineMany,final`
##      clusterIds color     name
## [1,] "-1"       "white"   "-1"
## [2,] "1"        "#A6CEE3" "c1"
## [3,] "2"        "#33A02C" "c2"
## [4,] "3"        "#B15928" "c3"
## [5,] "4"        "#1F78B4" "c4"
## [6,] "5"        "#FF7F00" "c5"
## [7,] "6"        "#6A3D9A" "c6"
## [8,] "7"        "#bd18ea" "c7"

We can see that each element of clusterLegend consists of a matrix, with number of rows equal to the number of clusters in the clustering. The columns store information about that cluster. clusterIds is the internal id (integer) used in clusterMatrix to identify the cluster, name is a name for the cluster, and color is a color for that cluster. color is used in plotting and visualizing the clusters, and name is an arbitrary character string for a cluster. They are automatically given default values when the ClusterExperiment object is created, but we will see under the description of visualization methods how the user might want to manipulate these for better plotting results. We can assign new values with a simple assignment operator. Here we change the internal cluster names of the first clustering from lowercase to uppercase “M”:

existingColors<-clusterLegend(ce)[[1]]
existingColors[,"name"]<-gsub("m","M",existingColors[,"name"])
clusterLegend(ce)[[1]]<-existingColors
print(ce)
## class: ClusterExperiment 
## dim: 7069 65 
## reducedDimNames: PCA 
## filterStats: var var_combineMany.final 
## -----------
## Primary cluster type: mergeClusters 
## Primary cluster label: mergeClusters 
## Table of clusters (of primary clustering):
## -1 M1 M2 M3 M4 
##  6 13 17 15 14 
## Total number of clusterings: 40 
## Dendrogram run on 'combineMany,final' (cluster index: 2)
## -----------
## Workflow progress:
## clusterMany run? Yes 
## combineMany run? Yes 
## makeDendrogram run? Yes 
## mergeClusters run? Yes

However, the user should not assign new values to clusterIds which must correspond to the internal ids of the clustering stored in the clustering matrix.

5 Visualizing the data

5.1 Cluster Alignment plot with plotClusters

We demonstrated during the quick start that we can visualize the alignment of multiple clusterings via a Cluster Alignment plot implemented in plotClusters or plotClustersWorkflow command. Since plotClustersWorkflow calls the plotClusters command and passes the arguments of plotClusters onward, we will focus mainly on the main plotClusters command, with the understanding that most of these arguments work for both.

Here is our basic call to plotClusters:

par(mar=plotCMar)
plotClusters(ce,main="Clusters from clusterMany", whichClusters="workflow", 
             axisLine=-1)

We have seen that we can get very different plots depending on how we order the clusterings, and what clusterings are included. The argument whichClusters allows the user to choose different clusterings or provide an explicit ordering of the clusterings. For plotClustersWorkflow, whichClusters indicates the clusterings that are “highlighted” by being drawn separately from the results of clusterMany.

whichClusters can take either a single character value, or a vector of either characters or indices. If whichClusters matches either “all” or “workflow”, then the clusterings chosen are either all, or only those from the most recent calls to the workflow functions. Choosing “workflow” removes from the visualization both user-defined clusterings and also previous calls to the workflow that have since been rerun. Setting whichClusters="workflow" can be a useful if you have called a method like combineMany several times, as we did, only with different parameters. All of those runs are saved (unless eraseOld=TRUE), but you may not want to plot them.

If whichClusters is a character that is not one of these designated values, the entries should match a “clusterType” value (like “clusterMany”) or a “clusterLabel” value (with exact matching). Alternatively, the user can specify numeric indices corresponding to the columns of clusterMatrix that provide the order of the clusters.

par(mar=plotCMar)
plotClusters(ce,whichClusters="clusterMany",
               main="Only Clusters from clusterMany",axisLine=-1)

We can also add to our plot (categorical) information on each of our subjects from the colData of our SummarizedExperiment object (which is also retained in our ClusterExperiment object). This can be helpful to see if the clusters correspond to other features of the samples, such as sample batches. Here we add the values from the columns “Biological_Condition” and “Published2” that were present in the fluidigm object and given with the published data.

par(mar=plotCMar)
plotClusters(ce,whichClusters="workflow", sampleData=c("Biological_Condition","Published2"), 
               main="Workflow clusters plus other data",axisLine=-1)