Package {fastrda}


Type: Package
Title: Fast Redundancy Analysis (RDA) with High-Performance 'C++' Backend
Version: 0.1.2
Description: Provides a high-performance implementation of redundancy analysis (RDA) in 'C++' using 'Armadillo' and 'OpenMP'. Supports standard and partial RDA, centering, scaling, overall and axis-wise permutation tests, biplot visualization, score extraction, and prediction. Designed for large ecological, genomic, and other multivariate data sets where computational speed and memory efficiency are important.
Depends: R (≥ 4.0.0)
Imports: Rcpp (≥ 1.0.0), parallel, ggplot2 (≥ 3.3.0)
Suggests: RhpcBLASctl, ggrepel (≥ 0.9.0), RColorBrewer (≥ 1.1-2), knitr, rmarkdown, vegan
LinkingTo: Rcpp, RcppArmadillo (≥ 0.12.0)
VignetteBuilder: knitr
License: GPL (≥ 3)
Encoding: UTF-8
SystemRequirements: OpenMP
Config/roxygen2/version: 8.0.0
NeedsCompilation: yes
Packaged: 2026-07-29 20:35:11 UTC; user1
Author: Zeynel Cebeci [aut, cre]
Maintainer: Zeynel Cebeci <cebeciz@gmail.com>
Repository: CRAN
Date/Publication: 2026-08-07 16:00:02 UTC

Biplot and Biplot Scores for fastrda Objects

Description

Computes vegan-compatible species and environmental biplot scores from a fitted fastrda object, and generates publication-ready ordination biplots using ggplot2.

Usage

biplot_scores(
  object,
  type = c("species", "environment", "both"),
  scaling = NULL,
  X = NULL,
  ...
)

biplotrda(
  x,
  axes = 1:2,
  type = c("all", "sites", "species", "environment", 
           "sites_species", "sites_environment"),
  scaling = 2,
  X = NULL,
  show_ids = FALSE,
  colpal = NULL,
  site_col = NULL,
  species_col = NULL,
  env_col = NULL,
  site_size = 2.5,
  arrow_size = 0.8,
  label_size = 3.5,
  arrow_scale = 1.5,
  alpha = 0.8,
  max_labels = 50,
  title = "fastrda Biplot",
  subtitle = NULL,
  theme = ggplot2::theme_minimal()
)

## S3 method for class 'fastrda_biplot'
print(x, ...)

## S3 method for class 'fastrda'
biplot(x, ...)

## S3 method for class 'fastrda'
plot(x, ...)

Arguments

object, x

A fitted fastrda object (or a fastrda_biplot object for print methods).

type

Character string specifying what to compute or display. For biplot_scores: "species", "environment", or "both". For biplotrda: "all", "sites", "species", "environment", "sites_species", or "sites_environment".

scaling

Integer (0-3) specifying the scaling type for scores. If NULL, uses the scaling from the original analysis model.

X

Optional matrix or data frame of environmental variables if not stored in the object.

axes

Integer vector of length 2 specifying the constrained axes to plot. Default is 1:2.

show_ids

Logical; if TRUE, displays site, species, or environmental variable labels. Default is FALSE.

colpal

Character string specifying a color palette name from RColorBrewer. Default is "Set1".

site_col

Custom color for site points (overrides palette).

species_col

Custom color for species arrows (overrides palette).

env_col

Custom color for environmental arrows (overrides palette).

site_size

Numeric; size of site points. Default is 2.5.

arrow_size

Numeric; thickness of arrows. Default is 0.8.

label_size

Numeric; size of labels. Default is 3.5.

arrow_scale

Numeric; scaling multiplier factor for biplot arrows. Default is 1.5.

alpha

Numeric; transparency value for points. Default is 0.8.

max_labels

Integer; maximum number of labels to display when show_ids = TRUE. Default is 50.

title

Character string for the plot title. Default is "fastrda Biplot".

subtitle

Character string for the plot subtitle. Default is NULL.

theme

ggplot2 theme object. Default is ggplot2::theme_minimal().

...

Additional arguments passed to lower-level plot or score functions.

Details

The function biplot_scores extracts or dynamically calculates site-weighted canonical coefficients and species scores conforming to the standard vegan package definitions across various scaling configurations (0 to 3). It seamlessly supports both matrix and list scaling structure formats in fastrda v1.4.4.

The function biplotrda (and its S3 generics biplot.fastrda and plot.fastrda) builds a customizable ggplot2 graphic supporting point layers for sites, vector arrows for species and environmental variables, automatic axis proportion variance labeling, and intelligent label overlapping control via ggrepel (if installed).

Value

For biplot_scores, returns a numeric matrix (if type is species or environment) or a list with species and environment components assigned to class fastrda_biplot.

For biplotrda, biplot.fastrda, and plot.fastrda, returns a ggplot2 object representing the ordination biplot.

For print.fastrda_biplot, invisibly returns the input object after printing summary text to the console.

See Also

fastrda, ordiplot

Examples

## Not run: 
set.seed(42)

n <- 30

env <- data.frame(
  Temperature = seq(10, 30, length.out = n),
  Moisture = rev(seq(20, 80, length.out = n)),
  pH = rnorm(n, 6.8, 0.4)
)

Y <- cbind(
  Sp1 = 1.2 * scale(env$Temperature) + rnorm(n, 0, 0.30),
  Sp2 = 0.9 * scale(env$Temperature) + rnorm(n, 0, 0.35),
  Sp3 = 1.1 * scale(env$Moisture) + rnorm(n, 0, 0.30),
  Sp4 = -0.9 * scale(env$Moisture) + rnorm(n, 0, 0.30),
  Sp5 = 1.0 * scale(env$pH) + rnorm(n, 0, 0.30),
  Sp6 = -0.8 * scale(env$pH) + rnorm(n, 0, 0.30)
)

fit <- fastrda(
  genotype = Y,
  environment = env,
  axes = 2,
  scaling = 2,
  keep_workspace = "none",
  verbose = FALSE
)

bp_scores <- biplot_scores(fit, type = "both")

bp_scores$environment
bp_scores$species

biplotrda(
  fit,
  axes = 1:2,
  scaling = 2,
  type = "all",
  show_ids = TRUE,
  title = "Simulated RDA Example"
)

## End(Not run)

Fast Redundancy Analysis and Associated Methods

Description

A high-performance implementation of Redundancy Analysis (RDA) and partial RDA using efficient QR decomposition, complete with integrated S3 methods for prediction, score extraction, permutation tests, summary reporting, and biplot visualization.

Usage

fastrda(
  genotype,
  environment,
  covariates = NULL,
  scale = TRUE,
  center = TRUE,
  axes = 3,
  scaling = 2,
  keep_workspace = "minimal",
  store_fitted = FALSE,
  threads = min(2, parallel::detectCores()),
  verbose = TRUE
)

## S3 method for class 'fastrda'
predict(
  object,
  newdata = NULL,
  type = c("lc", "response"),
  rank = NULL,
  scaling = NULL,
  ...
)

## S3 method for class 'fastrda'
scores(
  x, 
  display = c("both", "sites", "species", "wa", "lc"), 
  choices = 1:2, 
  scaling = NULL, 
  ...
)
                  
anova_fastrda(
  object,
  by = c("overall", "axis"),
  permutations = 999,
  threads = min(2, parallel::detectCores())
)

## S3 method for class 'fastrda'
anova(object, ...)

## S3 method for class 'fastrda'
print(x, ...)

## S3 method for class 'fastrda'
summary(object, ...)

## S3 method for class 'anova.fastrda'
print(x, ...)

## S3 method for class 'anova.fastrda.axis'
print(x, ...)

get_site_scores(object, scaling = 2)

Arguments

genotype

A numeric matrix or data frame of response variables (e.g., species abundances, genetic variants). Rows represent samples, columns represent variables.

environment

A numeric matrix or data frame of predictor variables. Rows must match the number of rows in genotype.

covariates

An optional numeric matrix or data frame of conditioning variables to be partialled out (partial RDA). Default is NULL.

scale

Logical; if TRUE, variables are scaled to unit variance before analysis. Default is TRUE.

center

Logical; if TRUE, variables are centered to zero mean before analysis. Default is TRUE.

axes

Integer; number of constrained axes to retain. Must be >= 1. Default is 3.

scaling

Integer (0-3); type of scaling for ordination scores:

0

No scaling.

1

Sites scaled by eigenvalue sqrt, species unscaled.

2

Sites unscaled, species scaled by eigenvalue sqrt (vegan default).

3

Symmetric scaling (both sites and species scaled by eigenvalue fourth root).

keep_workspace

Logical or character specifying workspace retention:

"minimal"

Store only Q and QtY (default).

"compact"

Store Q, QtY and Y_res.

"full"

Store all workspace elements.

"none"

Store no workspace.

store_fitted

Logical; if TRUE, stores fitted values in the output. Default is FALSE.

threads

Integer; number of threads for parallel computation. Defaults to number of available cores.

verbose

Logical; if TRUE, prints progress and summary messages. Default is TRUE.

object, x

A fitted fastrda object.

newdata

An optional matrix or data frame of new predictor variables for prediction.

type

Character string specifying the prediction type:

"lc"

Linear combination scores for new data.

"response"

Reconstructed response variables.

rank

Integer specifying the number of constrained axes to use for prediction or low-rank reconstruction.

choices

Integer vector specifying the constrained axes to extract.

by

Character string specifying the permutation test type:

"overall"

Global permutation test for the model.

"axis"

Marginal permutation test for each constrained axis.

permutations

Integer; number of permutations to perform. Default is 999.

display

Character string specifying what scores to extract:

"both"

Both sites and species scores.

"sites"

Site scores only.

"species"

Species scores only.

"wa"

Alias for site scores (vegan compatibility).

"lc"

Linear combination scores.

...

Additional arguments passed to other methods.

Details

Redundancy Analysis (RDA) is a multivariate constrained ordination method that finds linear combinations of environmental variables that best explain variation in response variables. It extends PCA by including explanatory variables.

fastrda implements RDA using a reduced-rank formulation based on efficient QR decomposition. For partial RDA models, conditioning variables are handled via Z-residualization.

Key Features:

High Performance

C++ core with OpenMP parallelization for large matrices.

Scaled Scores

Site and species scores are pre-computed for fast access.

Partial RDA

Support for conditioning variables.

Permutation Tests

Overall and axis-wise permutation tests.

vegan Compatibility

S3 methods mimic vegan interface.

Scaling Types: The scaling parameter controls how site and species scores are scaled:

scaling = 0

No scaling (raw scores).

scaling = 1

Site scores scaled by eigenvalue sqrt, species unscaled.

scaling = 2

Site scores unscaled, species scaled by eigenvalue sqrt (vegan default).

scaling = 3

Symmetric scaling (both scaled by eigenvalue fourth root).

Note on Adjusted R-squared: The semi-partial adjusted R^2 formulation computed in this version differs from the default implementation found in the vegan package.

Value

For fastrda, an object of class fastrda containing a list of model results:

site_scores

Pre-computed scaled site scores for the fitted scaling (access via fit$site_scores).

raw_site_scores

Unscaled site scores for flexible re-scaling.

species_scores

Pre-computed scaled species scores for the fitted scaling.

loadings

Species canonical coefficients/loadings.

coefficients

Environmental coefficients for the full-rank model.

lc_coefficients_raw

Raw linear combination coefficients.

eigenvalues

Eigenvalues of the constrained axes.

prop_total

Proportion of total inertia explained per axis.

prop_constrained

Proportion of constrained inertia explained per axis.

n_axes

Number of retained constrained axes.

n_samples

Number of samples (rows).

df_model

Model degrees of freedom.

df_resid

Residual degrees of freedom.

df_cond

Conditioning (partial) degrees of freedom.

total_inertia

Total inertia of the response matrix.

constrained_inertia

Inertia explained by constraints.

unconstrained_inertia

Residual inertia.

conditioned_inertia

Inertia removed by conditioning variables (partial RDA).

R2

Coefficient of determination.

adj_R2

Adjusted R-squared.

pseudo_F

Pseudo-F model statistic.

scaling_constants

Pre-computed scaling multipliers for all scaling types.

workspace

Workspace used for permutation tests (if retained).

call

Matched function call.

env_names

Column names of the environmental matrix.

species_names

Column names of the response matrix.

site_names

Row names of the response matrix.

For S3 methods and helper functions:

predict.fastrda

Returns either linear combination scores (type = "lc") or reconstructed response matrix (type = "response").

scores.fastrda

Returns a matrix of site scores or a list of site/species scores.

anova_fastrda

Returns an object of class anova.fastrda (overall test) or anova.fastrda.axis (axis-wise test).

get_site_scores

Returns site scores with optional re-scaling.

summary.fastrda

Invisibly returns the fastrda object after printing high-level model summaries.

See Also

biplotrda, biplot_scores, and rda for the reference implementation from the vegan package.

Examples

set.seed(123)
n <- 100
p <- 200
k <- 3
Y <- matrix(rnorm(n * p), n, p)
X <- matrix(rnorm(n * k), n, k)
Z <- matrix(rnorm(n * 2), n, 2)
colnames(Y) <- paste0("Sp", 1:p)
colnames(X) <- paste0("Env", 1:k)

# Fit standard RDA
fit <- fastrda(genotype = Y, environment = X, axes = 3, verbose = FALSE)

# Print model summary
summary(fit)

# Access pre-computed scores
head(fit$site_scores)
head(fit$species_scores)

# Fit partial RDA with covariates
fit_prda <- fastrda(genotype = Y, environment = X, covariates = Z, axes = 3, verbose = FALSE)

# Extract scores using S3 method
sc <- scores(fit, display = "both", choices = 1:2)

# Predict low-rank linear combination scores (rank = 1 path)
pred_lc <- predict(fit, type = "lc", rank = 1)

# Predict response matrix for new data
pred_resp <- predict(fit, newdata = X, type = "response")

# Get site scores with different scaling (e.g., scaling = 1)
site_sc <- get_site_scores(fit, scaling = 1)
head(site_sc)


# Permutation tests (isolated to respect CRAN execution time limits)
anv_overall <- anova(fit, permutations = 99)
print(anv_overall)

anv_axis <- anova_fastrda(fit, by = "axis", permutations = 99)
print(anv_axis)