| Title: | Unify Dimensionality Reduction Results |
|---|---|
| Description: | Dimensionality reduction is widely used in many domains for analyzing and visualizing high-dimensional data. 'tidydr' provides uniform output and is compatible with multiple methods, including 'prcomp', 'cmdscale', 'Rtsne', 'umap' and 'metaMDS'. Any function returning a numeric matrix can also be used. The unified result can be visualized directly with 'ggplot2', and several methods can be run and compared in a single call. |
| Authors: | Guangchuang Yu [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-6485-8781>), Shuangbin Xu [aut] (ORCID: <https://orcid.org/0000-0003-3513-5362>) |
| Maintainer: | Guangchuang Yu <[email protected]> |
| License: | Artistic-2.0 |
| Version: | 0.0.7 |
| Built: | 2026-10-13 12:13:53 UTC |
| Source: | https://github.com/yulab-smu/tidydr |
This function shows available methods that worked for dr() function.
available_methods(method = "all")available_methods(method = "all")
method |
one of 'data', 'distance' or 'all' (default) |
A character vector of available DR methods
Lang Zhou and Guangchuang Yu
available_methods()available_methods()
dimensional reduction
dr(data, fun, ...)dr(data, fun, ...)
data |
input data |
fun |
function to perform dimensional reduction |
... |
additional parameters passed to 'fun' |
This function call the user-provided function ('fun') to perform dimensional reduction on the input data ('data')
sample_info is an optional list that a dr_extract() method may return
alongside the coordinates. It is meant to carry method-specific, per-sample
information (e.g. local density, k-nearest-neighbour indices or cluster
labels). Every element of sample_info that holds one value per sample – a
vector or factor of length nrow(data) – is merged into the data.frame
returned by fortify(), using the element name as the column name, so that
it can be mapped in autoplot(). Elements that do not hold one value per
sample, and elements whose name is already taken by a coordinate or a
metadata column, are not merged and a warning is issued. None of the
dr_extract() methods shipped with the package returns a sample_info
element, so sample_info is NULL unless a custom dr_extract() method
supplies one.
a DrResult object, which contains 'data' (original data), 'drdata' (coordination after dimensionality reduction), eigenvalue (standard deviation explained by each dimension), stress (evaluate the effect of dimensionality reduction) and 'sample_info' (method-specific additional information, see Details)
Guangchuang Yu
x = dr(iris[,1:4], prcomp) autoplot(x, aes(color=.group), metadata=iris$Species)x = dr(iris[,1:4], prcomp) autoplot(x, aes(color=.group), metadata=iris$Species)
Compare several dimensionality reduction methods
dr_compare( data, funs = list(prcomp = stats::prcomp), dim = 1:2, metadata = NULL, ... )dr_compare( data, funs = list(prcomp = stats::prcomp), dim = 1:2, metadata = NULL, ... )
data |
input data. It follows the same contract as |
funs |
a named list of methods to compare. Each element is either a
function, or a list with components |
dim |
the two dimensions to extract, as a numeric vector of length 2.
Defaults to |
metadata |
optional sample-level metadata. It is forwarded to
|
... |
additional arguments passed to every method in |
dr_compare() applies several dimensionality reduction (DR) methods to the
same input data and collects their results, so that the methods can be
compared side by side. Every method is evaluated independently: a method that
fails, or that returns fewer dimensions than requested, does not interrupt
the others. The outcome of every method is reported in the summary
component, which is the main purpose of this function.
A method that fails is never given placeholder coordinates. The failure is
recorded in summary$error, and the corresponding element of results is
the condition (error) object, so it can be inspected further.
A DrCompare object, a list with the following components:
resultsa named list with one element per method. For a method that
ran successfully it is a DrResult (see dr()); for a method that failed
it is the condition (error) object.
summarya data.frame with one row per method and the columns
method, status, n, k, has_eigenvalue, has_stress and error.
status is "ok" if the method ran and returned at least max(dim)
dimensions, "insufficient_dims" if it ran but returned too few
dimensions, and "failed" if it raised an error. n and k are the
number of samples and the number of extracted dimensions,
has_eigenvalue and has_stress indicate whether the method produced
those quantities, and error holds the error message of a failed method
(NA otherwise).
dim, metadata, funs
the corresponding inputs, kept so that
autoplot() can rebuild the plot.
Guangchuang Yu
x <- dr_compare(iris[, 1:4], list(pca = stats::prcomp)) x$summary autoplot(x)x <- dr_compare(iris[, 1:4], list(pca = stats::prcomp)) x$summary autoplot(x)
dr_extract generic
dr_extract(result)dr_extract(result)
result |
DrResult object |
dr_extract() is an S3 generic. Methods are provided for the result classes
of the supported dimensionality reduction functions. In addition, a fallback
method is provided for plain numeric matrices: any function passed to dr()
that returns a numeric matrix with at least two columns is accepted, and its
columns are used as the reduced coordinates.
The list returned by a method must contain drdata, the reduced coordinates:
either a data.frame, or a numeric matrix, with one row per sample and at least
two columns (one per retained dimension). A matrix is converted to a
data.frame, so that fortify() – a 'ggplot2' generic – always returns a
data.frame. The columns are renamed Dim1, Dim2, ... by dr(), and a
drdata that is neither a data.frame nor a numeric matrix is rejected.
eigenvalue, stress and sample_info are optional. sample_info is a list
of method-specific, per-sample vectors (e.g. local density or cluster labels),
which fortify() merges into its result as extra columns; see dr() for the
details.
a list that contains components to construct a 'DrResult' object.
Guangchuang Yu
element_line2 for drawing shorten axis lines
element_line2( colour = NULL, size = NULL, linetype = NULL, lineend = NULL, color = NULL, arrow = NULL, inherit.blank = FALSE, id, xlength = 0.3, ylength = 0.3, ... )element_line2( colour = NULL, size = NULL, linetype = NULL, lineend = NULL, color = NULL, arrow = NULL, inherit.blank = FALSE, id, xlength = 0.3, ylength = 0.3, ... )
colour |
line colour |
size |
line size in pts |
linetype |
line type |
lineend |
line end style (round, butt, square) |
color |
aliase to colour |
arrow |
arrow specification, as created by 'grid::arrow()' |
inherit.blank |
whether inherit 'element_blank' |
id |
1 or 2, 1 for axis.line.x.bottom and 2 for axis.line.y.left, only these two axes supported |
xlength |
length of x axis |
ylength |
length of y axis |
... |
additional parameters |
element_line2 object, which is a tailored element_line object
Guangchuang Yu
Choose best K (number of clusters)
nk(data, k, fun = pam, ...)nk(data, k, fun = pam, ...)
data |
input data (a matrix, data frame, or 'dist' object) |
k |
a vector of candidate number of clusters |
fun |
a function to perform the clustering. It must accept the number of
clusters as its second argument, or through an argument named Whether |
... |
additional parameters passed to Note: by default this function calls |
This function calculate the silhouette scores of each K (number of clusters).
The output object can be used to choose the best K (via summary() or autoplot() methods)
The silhouette width is computed with cluster::silhouette() from the cluster
labels and the dissimilarity of data (stats::dist(data), unless data is
already a 'dist' object, in which case it is used as is). With the default
fun = cluster::pam the silhouette information that pam() computes itself is
reused verbatim, so the default result is unchanged.
Each element of $silinfo follows the shape produced by cluster::pam():
widths (a matrix with columns cluster, neighbor and sil_width),
clus.avg.widths (per-cluster averages) and avg.width (the overall average).
The row order of widths is the one produced by the clusterer, so it should be
aligned by sample name rather than by position.
a silinfo object, which contains 'data' (original data), 'silinfo' (silhouette scores), and k (the input k vector)
Guangchuang Yu
x <- nk(iris[,-5], 2:8) summary(x) # to visualize the average silhouete score (y axis) with k (x axis) autoplot(x) # to visualize a PCA plot color by the choosing k autoplot(x, k=3) # another clustering method x2 <- nk(iris[,-5], 2:4, fun = stats::kmeans) summary(x2) # a hierarchical method is cut automatically x3 <- nk(iris[,-5], 2:4, fun = stats::hclust) summary(x3)x <- nk(iris[,-5], 2:8) summary(x) # to visualize the average silhouete score (y axis) with k (x axis) autoplot(x) # to visualize a PCA plot color by the choosing k autoplot(x, k=3) # another clustering method x2 <- nk(iris[,-5], 2:4, fun = stats::kmeans) summary(x2) # a hierarchical method is cut automatically x3 <- nk(iris[,-5], 2:4, fun = stats::hclust) summary(x3)
Per-sample silhouette widths
silinfo_widths(x, k)silinfo_widths(x, k)
x |
a |
k |
a single value among the candidate |
Extract the fine-grained silhouette information of one k from an nk()
result: one row per sample, with the cluster the sample was assigned to, its
neighbour cluster and its silhouette width.
a data.frame with one row per sample and the columns sample,
cluster, neighbor and sil_width. The rows keep the order in which the
clusterer returned them – for cluster::pam() that is by cluster and, within
a cluster, by decreasing sil_width – so the rows should be aligned by
sample rather than by position. The per-cluster average silhouette widths
are attached as the "clus.avg.widths" attribute, and are also available as
x$silinfo[[i]]$clus.avg.widths, where i is the position of k in x$k.
Guangchuang Yu
x <- nk(iris[,-5], 2:4) head(silinfo_widths(x, 3)) attr(silinfo_widths(x, 3), "clus.avg.widths")x <- nk(iris[,-5], 2:4) head(silinfo_widths(x, 3)) attr(silinfo_widths(x, 3), "clus.avg.widths")
Dimensional reduction scatter plot axis theme
theme_dr( xlength = 0.3, ylength = 0.3, arrow = grid::arrow(length = unit(0.15, "inches"), type = "closed") )theme_dr( xlength = 0.3, ylength = 0.3, arrow = grid::arrow(length = unit(0.15, "inches"), type = "closed") )
xlength |
length of x axis |
ylength |
length of y axis |
arrow |
arrow specification, as created by 'grid::arrow()' |
a theme object with shorten axes
Guangchuang Yu
theme that remove axis
theme_noaxis(...)theme_noaxis(...)
... |
additional theme setting |
a theme object that disable axes
Guangchuang Yu