templates

4.1 matrix analyses

There is one matrix-analysis function in this course: runMatrixAnalysis(). If you meet older material calling runMatrixAnalyses(), with an “es” on the end, that was a wide-data-only version and it was retired in September 2026 — calling it now returns a message telling you what to use instead.

4.1.1 basic template: a wide data frame

A wide data frame has one row per sample and one column per analyte. chemical_blooms is exactly that shape: a label column naming each plant, and then one column for each compound class.


runMatrixAnalysis(
  data = chemical_blooms,
  analysis = "pca",
  columns_w_values_for_single_analyte = c(
    "Alkanes", "Sec_Alcohols", "Others", "Fatty_acids", "Alcohols",
    "Triterpenoids", "Ketones", "Other_compounds", "Aldehydes"
  ),
  columns_w_sample_ID_info = c("label")
)

That is the whole basic call, and it is only four questions:

  • data — which table.
  • analysis — which analysis. "pca", "hclust", "kmeans", "dist" and the rest are listed in the full template below.
  • columns_w_values_for_single_analyte — which columns hold the numbers. One column per analyte.
  • columns_w_sample_ID_info — which column (or columns) name a sample. If it takes two columns together to identify a sample, list both.

If your data are long instead — one row per sample per analyte, with the analyte names stacked in a single column — then swap columns_w_values_for_single_analyte for the pair column_w_names_of_multiple_analytes and column_w_values_for_multiple_analytes. Everything else stays the same.

4.1.2 full template


runMatrixAnalysis(
  data, # data to use for analysis
  analysis = c(
      "pca", "pca_ord", "pca_dim", # PCA
      "mca", "mca_ord", "mca_dim", # MCA (PCA on categorical data)
      "mds", "mds_ord", "mds_dim", # MDS
      "tsne", "dbscan", "kmeans", # Clustering
      "hclust", "hclust_phylo" # Hierarchical clustering
  ),
  parameters = NULL,
  column_w_names_of_multiple_analytes = NULL,
  column_w_values_for_multiple_analytes = NULL,
  columns_w_values_for_single_analyte = NULL,
  columns_w_additional_analyte_info = NULL,
  columns_w_sample_ID_info = NULL,
  transpose = FALSE, # default = FALSE, this chooses whether to transpose the data
  distance_method = c( # the distance metric to use in computing a distance matrix
    "euclidean", "manhattan",
    "gower" # for mixed numeric / categorical data; computed with cluster::daisy
  ),
  agglomeration_method = c( # the clustering method to use in heirarchical clustering
      "ward.D2", "ward.D", "single", "complete",
      "average", # (= UPGMA)
      "mcquitty", # (= WPGMA)
      "median", # (= WPGMC)
      "centroid" # (= UPGMC)
  ),
  tree_method = c( # how a tree is built, for analysis = "hclust" / "hclust_phylo"
    "linkage_dendrogram", # DEFAULT. Hierarchical clustering proper: uses agglomeration_method,
                          # and returns bootstrap support values.
    "neighbor_joining"    # The phylogenetic method. Works from the distance matrix alone, so it
                          # IGNORES agglomeration_method, and gives no bootstrap values.
  ),
  unknown_sample_ID_info = NULL,
  components_to_return = 2, # how many principal components to return
  scale_variance = NULL, # default = TRUE for EVERY analysis: centers each column and divides it by
                         # its standard deviation, so no single large-valued variable dominates the
                         # distances. Pass FALSE for compositional data (every column a share of the
                         # same whole), where the columns are already on one scale.
  na_replacement = c("mean", "none", "zero", "drop"), # default = "mean", this chooses what to do with missing values
  output_format = c("wide", "long"), # default = "wide". For analysis = "dist" this chooses the
                                     # RETURN TYPE: "wide" gives a base R `dist` object, "long"
                                     # gives one row per PAIR of samples, which is what you want
                                     # if you are about to build a network from the distances.
)

4.2 models

Models in this course use two functions: buildModel() builds a model from a table, and predictWithModel() uses that model to make predictions for a table. (If you meet older material calling buildModel2(), it is the same function under its old name.)

4.2.1 basic template: one predictor, one response


my_model <- buildModel(
  data = metabolomics_data,
  model_type = "linear_regression",
  predictors = "iso-Leucine",
  response = "Valine"
)

my_predictions <- predictWithModel(
  data = metabolomics_unknown,
  model = my_model
)

That is the whole basic workflow, and buildModel() is only four questions:

  • data: which table to build the model from. It must have no missing values in the columns the model uses (fill them in with impute() or remove those rows first).
  • model_type: which kind of model. The options are listed in the full template below.
  • predictors: which column (or columns) the model predicts from. For more than one, use c("col_1", "col_2").
  • response: which one column the model predicts.

predictWithModel() is only two questions: which table to predict for (data), and which model to use (model, the whole output of buildModel()). The new table needs every predictor column, but it does not need the response. What comes back is that same table with new columns added:

  • regression models add predicted_<response>, for example predicted_Valine.
  • classification models add one probability_<class> column per class, plus predicted_class.

4.2.2 full template: buildModel()


buildModel(
  data, # the table to build the model from; no missing values in the columns the model uses
  model_type = c(
    "linear_regression",            # predicts a number with a straight-line relationship
    "random_forest_regression",     # predicts a number with a random forest
    "random_forest_classification", # predicts a category with a random forest
    "logistic_regression",          # predicts one of two categories
    "contrastive_learning"          # builds an embedding rather than a prediction
  ),
  predictors = NULL, # the column(s) to predict from, e.g. c("iso-Leucine", "Leucine")
  response = NULL,   # the one column to predict
  formula = NULL, # an alternative to predictors + response, for linear_regression only:
                  #   response ~ predictor                 one predictor
                  #   response ~ predictor_1 + predictor_2 each group its own intercept,
                  #                                        one shared slope
                  #   response ~ predictor_1 * predictor_2 each group its own intercept AND slope
                  # Give either formula, or predictors and response, never both.
  scale_variance = FALSE, # TRUE scales each numeric predictor to mean 0 and standard deviation 1
                          # before fitting, so coefficients can be compared across predictors.
                          # The response is never scaled. predictWithModel() scales new data the
                          # same way automatically, so new tables always go in as measured.
  fold_cross_validation = 10, # random forests only: the number of folds used in cross-validation
                              # (2 or more)
  optimization_parameters = list( # random forests only: the grid of settings to try
    n_vars_tried_at_split = seq(10, 20, 5), # how many predictors each split may choose from
    n_trees = seq(100, 200, 50),            # how many trees in the forest
    min_leaf_size = 1                       # the fewest samples allowed in a leaf
  )
)

The output is a list. The parts you will use most:

  • $model_type, $response and $predictors: what the model is and what it relates.
  • $model: the fitted model itself.
  • $metrics: how well the model performs.

4.2.3 full template: predictWithModel()


predictWithModel(
  data,  # the table to predict for; it needs every predictor column the model was built on
  model  # the output of buildModel() (the whole list, or just its $model)
)

predictWithModel() works out the model type from the model itself, so you never need to tell it. It can only predict for groups the model has seen: if the new table contains a category that was not in the table used to build the model, it stops and says so.