% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/netConstruct.R
\name{netConstruct}
\alias{netConstruct}
\title{Constructing Networks for Microbiome Data}
\usage{
netConstruct(data,
             data2 = NULL,
             dataType = "counts",
             group = NULL,
             matchDesign = NULL,
             taxRank = NULL,
             
             # Association/dissimilarity measure:
             measure = "spieceasi",
             measurePar = NULL,
             
             # Preprocessing:
             jointPrepro = NULL,
             filtTax = "none",
             filtTaxPar = NULL,
             filtSamp = "none",
             filtSampPar = NULL,
             zeroMethod = "none",
             zeroPar = NULL,
             normMethod = "none",
             normPar = NULL,
             
             # Sparsification:
             sparsMethod = "t-test",
             thresh = 0.3,
             alpha = 0.05,
             adjust = "adaptBH",
             trueNullMethod = "convest",
             lfdrThresh = 0.2,
             nboot = 1000L,
             assoBoot = NULL,
             cores = 1L,
             logFile = "log.txt",
             softThreshType = "signed",
             softThreshPower = NULL,
             softThreshCut = 0.8,
             kNeighbor = 3L,
             knnMutual = FALSE,
             
             # Transformation:
             dissFunc = "signed",
             dissFuncPar = NULL,
             simFunc = NULL,
             simFuncPar = NULL,
             scaleDiss = TRUE,
             weighted = TRUE,
             
             # Further arguments:
             sampleSize = NULL,
             verbose = 2,
             seed = NULL
             )
}
\arguments{
\item{data}{numeric matrix. Can be a count matrix (rows are samples, columns
are OTUs/taxa), a phyloseq object, or an association/dissimilarity matrix
(\code{dataType} must be set).
a second count matrix/phyloseq object or a second association/dissimilarity
matrix.}

\item{data2}{optional numeric matrix used for constructing a second 
network (belonging to group 2). Can be either a second count 
matrix/phyloseq object or a second association/dissimilarity matrix.}

\item{dataType}{character indicating the data type. Defaults to "counts",
which means that \code{data} (and data2) is a count matrix or object of
class \code{\link[phyloseq:phyloseq-class]{phyloseq}}. Further options
are "correlation", "partialCorr" (partial correlation), "condDependence"
(conditional dependence), "proportionality" and "dissimilarity".}

\item{group}{optional binary vector used for splitting the data into two
groups. If \code{group} is \code{NULL} (default) and \code{data2} is not 
set, a single network is constructed. See 'Details.'}

\item{matchDesign}{Numeric vector with two elements specifying an optional 
matched-group (i.e. matched-pair) design, which is used for the permutation 
tests in \code{\link{netCompare}} and \code{\link{diffnet}}. \code{c(1,1)} 
corresponds to a matched-pair design. A 1:2 matching, for instance, is 
defined by \code{c(1,2)}, which means that the first sample of group 1 is 
matched to the first two samples of group 2 and so on. 
The appropriate order of samples must be ensured. If 
\code{NULL}, the group memberships are shuffled randomly while group sizes
identical to the original data set are ensured.}

\item{taxRank}{character indicating the taxonomic rank at which the network 
should be constructed. Only used if data (and data 2) is a phyloseq object. 
The given rank must match one of the column names of the taxonomic table 
(the \code{@tax_table} slot of the phyloseq object). Taxa names of the 
chosen taxonomic rank must be unique (consider using the function 
\code{\link{renameTaxa}} to make them unique). If a phyloseq object is 
given and \code{taxRank = NULL}, the row names of the OTU table are used 
as node labels.}

\item{measure}{character specifying the method used for either computing the
associations between taxa or dissimilarities between subjects.
Ignored if \code{data} is not a count matrix (if \code{dataType} is not set
to \code{"counts"}). Available measures are:
\code{"pearson"}, \code{"spearman"}, \code{"bicor"}, \code{"sparcc"},
\code{"cclasso"}, \code{"ccrepe"}, \code{"spieceasi"} (default),
\code{"spring"}, \code{"gcoda"} and \code{"propr"} as association measures,
and \code{"euclidean"}, \code{"bray"}, \code{"kld"}, \code{"jeffrey"},
\code{"jsd"}, \code{"ckld"}, and \code{"aitchison"} as dissimilarity
measures. Parameters are set via \code{measurePar}.}

\item{measurePar}{list with parameters passed to the function for computing
associations/dissimilarities. See 'Details' for the respective functions. 
For SpiecEasi or SPRING as association measure, an additional list element
"symBetaMode" is accepted to define the "mode" argument of 
\code{\link[SpiecEasi]{symBeta}}.}

\item{jointPrepro}{logical indicating whether data preprocessing (filtering,
zero treatment, normalization) should be done for the combined data sets,
or each data set separately. Ignored if a single network is constructed.
Defaults to \code{TRUE} if \code{group} is given, and to \code{FALSE} if
\code{data2} is given. Joint preprocessing is not possible for 
dissimilarity networks.}

\item{filtTax}{character indicating how taxa shall be filtered. Possible
options are:
\describe{
\item{\code{"none"}}{Default. All taxa are kept.}
\item{\code{"totalReads"}}{Keep taxa with a total number
of reads of at least x.}
\item{\code{"relFreq"}}{Keep taxa whose number of reads is at
least x\% of the total number of reads.}
\item{\code{"numbSamp"}}{Keep taxa observed in at least x samples.}
\item{\code{"highestVar"}}{Keep the x taxa with highest variance.}
\item{\code{"highestFreq"}}{Keep the x taxa with highest frequency.}
}
Except for "highestVar" and "highestFreq", different filter methods can be
combined. The values x are set via \code{filtTaxPar}.}

\item{filtTaxPar}{list with parameters for the filter methods given by
\code{filtTax}. Possible list entries are: \code{"totalReads"} (int),
\code{"relFreq"} (value in [0,1]), \code{"numbSamp"} (int),
\code{"highestVar"} (int), \code{"highestFreq"} (int).}

\item{filtSamp}{character indicating how samples shall be filtered. Possible
options are: \describe{
\item{\code{"none"}}{Default. All samples are kept.}
\item{\code{"totalReads"}}{Keep samples with a total number of reads of at
least x.}
\item{\code{"numbTaxa"}}{Keep samples for which at least
x taxa are observed.}
\item{\code{"highestFreq"}}{Keep the x samples with highest frequency.}}
Except for "highestFreq", different filter methods can be
combined. The values x are set via \code{filtSampPar}.}

\item{filtSampPar}{list with parameters for the filter methods given by
\code{filtSamp}. Possible list entries are: \code{"totalReads"} (int),
\code{"numbTaxa"} (int), \code{"highestFreq"} (int).}

\item{zeroMethod}{character indicating the method used for zero replacement.
Possible values are: \code{"none"} (default), \code{"pseudo"}, 
\code{"pseudoZO"}, \code{"multRepl"}, \code{"alrEM"}, \code{"bayesMult"}. 
See 'Details'. The corresponding parameters are set via \code{zeroPar}. 
\code{zeroMethod} is ignored if the approach for
calculating the associations/dissimilarity includes zero handling.
Defaults to \code{"multRepl"} or \code{"pseudo"} (depending on the expected
input of the normalization function and measure) if zero replacement is
required.}

\item{zeroPar}{list with parameters passed to the function for zero
replacement (\code{zeroMethod}). See the help page of the respective
function for details. If \code{zeroMethod} is \code{"pseudo"} or 
\code{"pseudoZO"}, the pseudo count can be specified via 
\code{zeroPar = list(pseudocount = x)} (where x is numeric).}

\item{normMethod}{character indicating the normalization method (to
make counts of different samples comparable). Possible options are:
\code{"none"} (default), \code{"TSS"} (or \code{"fractions"}), \code{"CSS"},
\code{"COM"}, \code{"rarefy"}, \code{"VST"}, \code{"clr"}, and 
\code{"mclr"}. See 'Details'. The corresponding parameters are set via 
\code{normPar}.}

\item{normPar}{list with parameters passed to the function for normalization
(defined by \code{normMethod}).}

\item{sparsMethod}{character indicating the method used for sparsification
(selected edges that are connected in the network). Available methods are:
\describe{
\item{\code{"none"}}{Leads to a fully connected network}
\item{\code{"t-test"}}{Default. Associations being significantly different 
from zero are selected using Student's t-test. Significance level and 
multiple testing adjustment is specified via \code{alpha} and 
\code{adjust}. \code{sampleSize} must be set if \code{dataType} is not 
"counts".}
\item{\code{"bootstrap"}}{Bootstrap procedure as described in
\cite{Friedman and Alm (2012)}. Corresponding arguments are
\code{nboot}, \code{cores}, and \code{logFile}. Data type must be 
"counts".}
\item{\code{"threshold"}}{Selected are taxa
pairs with an absolute association/dissimilarity greater than or equal to
the threshold defined via \code{thresh}.}
\item{\code{"softThreshold"}}{Soft thresholding method according to
\cite{Zhang and Horvath (2005)} available in the
\code{\link[WGCNA:pickSoftThreshold]{WGCNA}} package. Corresponding
arguments are \code{softThreshType}, \code{softThreshPower}, and
\code{softThreshCut}.}
\item{\code{"knn"}}{Construct a k-nearest neighbor or mutual k-nearest
neighbor graph using \code{\link[cccd]{nng}}. Corresponding
arguments are \code{kNeighbor}, and \code{knnMutual}. Available for 
dissimilarity networks only.}}}

\item{thresh}{numeric vector with one or two elements defining the threshold 
used for sparsification if \code{sparsMethod} is set to \code{"threshold"}. 
If two networks are constructed and one value is given, it is used 
for both groups. Defaults to 0.3.}

\item{alpha}{numeric vector with one or two elements indicating the 
significance level. Only used if Student's t-test or bootstrap
procedure is used as sparsification method. If two networks are constructed 
and one value is given, it is used for both groups. Defaults to 0.05.}

\item{adjust}{character indicating the method used for multiple testing
adjustment (if Student's t-test or bootstrap procedure is used for edge
selection). Possible values are \code{"lfdr"} (default) for local
false discovery rate correction (via \code{\link[fdrtool]{fdrtool}}),
\code{"adaptBH"} for the adaptive Benjamini-Hochberg method
\cite{(Benjamini and Hochberg, 2000)}, or one of the methods provided by
\code{\link[stats]{p.adjust}} (see \code{p.adjust.methods()}.}

\item{trueNullMethod}{character indicating the method used for estimating the
proportion of true null hypotheses from a vector of p-values. Used for the
adaptive Benjamini-Hochberg method for multiple testing adjustment (chosen
by \code{adjust = "adaptBH"}). Accepts the provided options of the
\code{method} argument of \code{\link[limma]{propTrueNull}}:
\code{"convest"}(default), \code{"lfdr"}, \code{"mean"}, and \code{"hist"}.
Can alternatively be \code{"farco"} for
the "iterative plug-in method" proposed by \cite{Farcomeni (2007)}.}

\item{lfdrThresh}{numeric vector with one or two elements defining the 
threshold(s) for local FDR correction (if \code{adjust = "locfdr"}). 
Defaults to 0.2 meaning that associations with a
corresponding local FDR less than or equal to 0.2 are identified as
significant. If two networks are constructed and one value is given, it is 
used for both groups.}

\item{nboot}{integer indicating the number of bootstrap samples, if
bootstrapping is used as sparsification method.}

\item{assoBoot}{logical or list. Only relevant for bootstrapping. 
Set to \code{TRUE} if a list (\code{assoBoot}) with bootstrap association 
matrices should be returned. Can also be a list with bootstrap 
association matrices, which are used for sparsification. See the example.}

\item{cores}{integer indicating the number of CPU cores used for
bootstrapping. If cores > 1, bootstrapping is performed parallel.
\code{cores} is limited to the number of available CPU cores determined by
\code{\link[parallel]{detectCores}}. Then, core arguments of the function 
used for association estimation (if provided) should be set to 1.}

\item{logFile}{character defining a log file to which the iteration numbers 
are stored if bootstrapping is used for sparsification. The file is written 
to the current working directory. Defaults to \code{"log.txt"}. 
If\code{ NULL}, no log file is created.}

\item{softThreshType}{character indicating the method used for transforming
correlations into similarities if soft thresholding is used as sparsification
method (\code{sparsMethod = "softThreshold"}). Possible values are
\code{"signed"}, \code{"unsigned"}, and \code{"signed hybrid"} (according
to the available options for the argument \code{type} of
\code{\link[WGCNA]{adjacency}} from \code{WGCNA} package).}

\item{softThreshPower}{numeric vector with one or two elements defining the 
power for soft thresholding. Only used if
\code{edgeSelect = "softThreshold"}. If two networks are constructed and 
one value is given, it is used for both groups. If no power is set, it is 
computed using \code{\link[WGCNA]{pickSoftThreshold}}, where the argument
\code{softThreshCut} is needed in addition.}

\item{softThreshCut}{numeric vector with one or two elements (each between 0 
and 1) indicating the desired minimum scale free topology fitting index 
(corresponds to the argument "RsquaredCut" in 
\code{\link[WGCNA]{pickSoftThreshold}}). Defaults to 0.8.
If two networks are constructed and one value is given, it is 
used for both groups.}

\item{kNeighbor}{integer specifying the number of neighbors if the k-nearest
neighbor method is used for sparsification. Defaults to 3L.}

\item{knnMutual}{logical used for k-nearest neighbor sparsification. If
\code{TRUE}, the neighbors must be mutual. Defaults to \code{FALSE}.}

\item{dissFunc}{method used for transforming associations into 
dissimilarities. Can be a character with one of the following values: 
\code{"signed"}(default), \code{"unsigned"}, \code{"signedPos"}, 
\code{"TOMdiss"}.
Alternatively, a function is accepted with the association matrix as first
argument and optional further arguments, which can be set via
\code{dissFuncPar}. Ignored for dissimilarity measures. See 'Details.'}

\item{dissFuncPar}{optional list with parameters if a function is passed to
\code{dissFunc}.}

\item{simFunc}{function for transforming dissimilarities into
similarities. Defaults to f(x)=1-x for dissimilarities in [0,1], and
f(x)=1/(1 + x) otherwise.}

\item{simFuncPar}{optional list with parameters for the function passed to
\code{simFunc}.}

\item{scaleDiss}{logical. Indicates whether dissimilarity values should be
scaled to [0,1] by (x - min(dissEst)) / (max(dissEst) - min(dissEst)),
where dissEst is the matrix with estimated dissimilarities.
Defaults to \code{TRUE}.}

\item{weighted}{logical. If \code{TRUE}, similarity values are used as
adjacencies. \code{FALSE} leads to a binary adjacency matrix whose entries
equal 1 for (sparsified) similarity values > 0, and 0 otherwise.}

\item{sampleSize}{numeric vector with one or two elements giving the number 
of samples that have been used for computing the association matrix. 
Only needed if an association matrix
is given instead of a count matrix and if, in addition, Student's t-test is
used for edge selection. If two networks are constructed and one value is 
given, it is used for both groups.}

\item{verbose}{integer indicating the level of verbosity. Possible values:
\code{"0"}: no messages, \code{"1"}: only important messages,
\code{"2"}(default): all progress messages, \code{"3"} messages returned 
by external functions are shown in addition. Can also be logical.}

\item{seed}{integer giving a seed for reproducibility of the results.}
}
\value{
An object of class \code{microNet} containing the following elements:
  \tabular{ll}{
  \code{edgelist1, edgelist2}\tab Edge list with the following columns:
  \itemize{
 \item \code{v1}, \code{v2}: names of adjacent nodes/vertices
 \item \code{asso}: estimated association (only for association networks)
 \item \code{diss}: dissimilarity
 \item \code{sim}: similarity (only for unweighted networks)
 \item \code{adja}: adjacency (equals similarity for 
  weighted networks)
 }\cr
  \code{assoMat1, assoMat2}\tab Sparsified associations (\code{NULL} for
  dissimilarity based networks)\cr
  \code{dissMat1, dissMat2}\tab Sparsified dissimilarities (for association
  networks, these are the sparsified associations transformed into
  dissimilarities)\cr
  \code{simMat1, simMat2}\tab Sparsified similarities\cr
  \code{adjaMat1, adjaMat2}\tab Adjacency matrices\cr
  \code{assoEst1, assoEst2}\tab Estimated associations (\code{NULL} for
  dissimilarity based networks)\cr
  \code{dissEst1, dissEst2}\tab Estimated dissimilarities (\code{NULL} for
  association networks)\cr
  \code{dissScale1, dissScale2}\tab Scaled dissimilarities (\code{NULL} for
  association networks)\cr
  \code{assoBoot1, assoBoot2}\tab List with association matrices for the 
  bootstrap samples. Returned if bootstrapping is used for 
  sparsification and \code{assoBoot} is \code{TRUE}.\cr
  \code{countMat1, countMat2}\tab Count matrices after filtering but before
  zero replacement and normalization. Only returned if \code{jointPrepro}
  is \code{FALSE} or for a single network.\cr
  \code{countsJoint}\tab Joint count matrix after filtering but before
  zero replacement and normalization. Only returned if \code{jointPrepro}
  is \code{TRUE}.\cr
  \code{normCounts1, normCounts2}\tab Count matrices after zero handling and
  normalization\cr
  \code{groups}\tab Names of the factor levels according to which the groups
  have been built\cr
  \code{softThreshPower}\tab Determined (or given) power for
  soft-thresholding.\cr
  \code{assoType}\tab Data type (either given by \code{dataType} or
  determined from \code{measure})\cr
  \code{twoNets}\tab Indicates whether two networks have been constructed\cr
  \code{parameters}\tab Parameters used for network construction}
}
\description{
Constructing microbial association networks and dissimilarity
  based networks (where nodes are subjects) from compositional count data.
}
\details{
The object returned by \code{netConstruct} can either be passed to
  \code{\link{netAnalyze}} for network analysis, or to
  \code{\link{diffnet}} to construct a differential network from the
  estimated associations.
  \cr
  The function enables the construction of either a \strong{single network} 
  or \strong{two networks}. The latter can be compared using the function
  \code{\link{netCompare}}. 
  \cr\cr
  The network(s) can either be based on \strong{associations} (correlation,
  partial correlation / conditional dependence, proportionality) or 
  \strong{dissimilarities}. Several measures are available, respectively, 
  to estimate associations or dissimilarities using \code{netConstruct}. 
  Alternatively, a pre-generated association or dissimilarity matrix is 
  accepted as input to start the workflow (argument \code{dataType} must be 
  set appropriately). 
  Depending on the measure, network nodes are either taxa or subjects: 
  In association-based networks nodes are taxa, whereas in 
  dissimilarity-based networks nodes are subjects.
  \cr
  \cr
  In order to perform a \strong{network comparison}, the following options 
  for constructing two networks are available:
  \enumerate{
    \item Passing the combined count matrix to \code{data} and a group 
    vector to \code{group} (of length \code{nrow(data)} for association 
    networks and of length \code{ncol(data)} for dissimilarity-based 
    networks).
    \item Passing the count data for group 1 to \code{data} (matrix or
    phyloseq object) and the count data for group 2 to \code{data2} (matrix 
    or phyloseq object). For association networks, the column names must 
    match, and for dissimilarity networks the row names.
    \item Passing an association/dissimilarity matrix for group 1 to 
    \code{data} and an association/dissimilarity matrix for group 2 to 
    \code{data2}.
  }
  \cr
  \strong{Group labeling:}\cr 
  If two networks are generated, the network belonging to \code{data} 
  is always denoted by "group 1" and the network belonging to \code{data2} 
  by "group 2".\cr
  If a group vector is used for splitting the data into two groups, the group
  names are assigned according to the order of group levels. If \code{group}
  contains the levels 0 and 1, for instance, "group 1" is assigned to level 0
  and "group 2" is assigned to level 1. \cr
  In the network plot, group 1 is shown on the left and group 2 on the 
  right if not defined otherwise (see \code{\link{plot.microNetProps}}).
  \cr\cr
  \strong{Association measures}
  \tabular{ll}{
  Argument \tab Function\cr
  \code{"pearson"}\tab \code{\link[stats]{cor}} \cr
  \code{"spearman"}\tab \code{\link[stats]{cor}} \cr
  \code{"bicor"}\tab \code{\link[WGCNA]{bicor}} \cr
  \code{"sparcc"}\tab \code{\link[SpiecEasi]{sparcc}} \cr
  \code{"cclasso"}\tab \code{\link[NetCoMi]{cclasso}} \cr
  \code{"ccrepe"}\tab \code{\link[ccrepe]{ccrepe}} \cr
  \code{"spieceasi"}\tab \code{\link[SpiecEasi]{spiec.easi}} \cr
  \code{"spring"}\tab \code{\link[SPRING]{SPRING}} \cr
  \code{"gcoda"}\tab \code{\link[NetCoMi]{gcoda}} \cr
  \code{"propr"}\tab \code{\link[propr]{propr}}}
  \cr
  \strong{Dissimilarity measures}
  \tabular{lll}{
  Argument \tab Function \tab Measure\cr
  \code{"euclidean"} \tab \code{\link[vegan]{vegdist}} \tab
  Euclidean distance \cr
  \code{"bray"}\tab \code{\link[vegan]{vegdist}} \tab
  Bray-Curtis  dissimilarity \cr
  \code{"kld"}\tab \code{\link[LaplacesDemon]{KLD}} \tab
  Kullback-Leibler divergence \cr
  \code{"jeffrey"}\tab \code{\link[LaplacesDemon]{KLD}} \tab
  Jeffrey divergence\cr
  \code{"jsd"}\tab \code{\link[LaplacesDemon]{KLD}} \tab
  Jensen-Shannon divergence \cr
  \code{"ckld"}\tab \code{\link[base]{log}} \tab
  Compositional Kullback-Leibler divergence \cr
  \code{"aitchison"}\tab \code{\link[vegan]{vegdist}},
  \code{\link[robCompositions]{cenLR}}\tab
  Aitchison distance}
  Definitions:\cr
  \describe{
  \item{Kullback-Leibler divergence:}{Since KLD is not symmetric,
  0.5 * (KLD(p(x)||p(y)) + KLD(p(y)||p(x))) is returned.}
  \item{Jeffrey divergence:}{Jeff = KLD(p(x)||p(y)) + KLD(p(y)||p(x))}
  \item{Jensen-Shannon divergence:}{JSD = 0.5 KLD(P||M) + 0.5 KLD(Q||M),
  where P=p(x), Q=p(y), and M=0.5(P+Q).}
  \item{Compositional Kullback-Leibler divergence:}{cKLD(x,y) =
  p/2 * log(A(x/y) * A(y/x)), where A(x/y) is the arithmetic mean of the
  vector of ratios x/y.}
  \item{Aitchison distance:}{Euclidean distance of the clr-transformed data.}
  }\cr
  \strong{Methods for zero replacement}
  \tabular{lll}{
  Argument \tab Method \tab Function\cr
  \code{"none"} \tab No zero replacement (only available if no zero
  replacement is needed for the chosen normalization method and 
  association/dissimilarity measure).\tab -\cr
  \code{"pseudo"} \tab A pseudo count (defined by \code{pseudocount} as 
  optional element of \code{zeroPar}) is added to all counts. A unit zero 
  count is used by default.\tab -\cr
  \code{"pseudoZO"} \tab A pseudo count (defined by \code{pseudocount} as 
  optional element of \code{zeroPar}) is added to zero counts only. 
  A unit zero count is used by default.\tab -\cr
  \code{"multRepl"} \tab Multiplicative simple replacement \tab
 \code{\link[zCompositions:multRepl]{multRepl}}\cr
  \code{"alrEM"} \tab Modified EM alr-algorithm 
  \tab \code{\link[zCompositions:lrEM]{lrEM}}\cr
  \code{"bayesMult"} \tab Bayesian-multiplicative replacement\tab
  \code{\link[zCompositions:cmultRepl]{cmultRepl}}\cr
  }
  \strong{Normalization methods}
  \tabular{lll}{
  Argument \tab Method \tab Function\cr
  \code{"TSS"} \tab Total sum scaling \tab t(apply(countMat, 1, function(x)
  x/sum(x)))\cr
  \code{"CSS"} \tab Cumulative sum scaling \tab
  \code{\link[metagenomeSeq]{cumNormMat}}\cr
  \code{"COM"} \tab Common sum scaling \tab
  t(apply(countMat, 1, function(x) x * min(rowSums(countMat)) / sum(x)))\cr
  \code{"rarefy"} \tab Rarefying \tab \code{\link[vegan:rarefy]{rrarefy}}\cr
  \code{"VST"} \tab Variance stabilizing transformation\tab
  \code{\link[DESeq2]{varianceStabilizingTransformation}}\cr
  \code{"clr"} \tab Centered log-ratio transformation\tab
  \code{\link[SpiecEasi]{clr}}\cr
  \code{"mclr"} \tab Modified central log ratio transformation\tab
  \code{\link[SPRING]{mclr}}
  }
  These methods (except for rarefying) are described in
  \cite{Badri et al.(2020)}.
  \cr\cr
  \strong{Transformation methods}\cr
  Functions used for transforming associations into dissimilarities:
  \tabular{ll}{
  Argument \tab Function\cr
  \code{"signed"} \tab sqrt(0.5 * (1 - x))\cr
  \code{"unsigned"} \tab sqrt(1 - x^2)\cr
  \code{"signedPos"} \tab  diss <- sqrt(0.5 * (1-x))\cr
    \tab diss[x < 0] <- 0\cr
  \code{"TOMdiss"} \tab \code{\link[WGCNA:TOMsimilarity]{TOMdist}}
  }
}
\examples{
# Load data sets from American Gut Project (from SpiecEasi package)
data("amgut1.filt")
data("amgut2.filt.phy")

# Single network with the following specifications:
# - Association measure: SpiecEasi
# - SpiecEasi parameters are defined via 'measurePar' 
#   (check ?SpiecEasi::spiec.easi for available options)
# - Note: 'rep.num' should be higher for real data sets
# - Taxa filtering: Keep the 50 taxa with highest variance
# - Sample filtering: Keep samples with a total number of reads 
#   of at least 1000

net1 <- netConstruct(amgut2.filt.phy, 
                     measure = "spieceasi",
                     measurePar = list(method = "mb",
                                       pulsar.params = list(rep.num = 10),
                                       symBetaMode = "ave"),
                     filtTax = "highestVar",
                     filtTaxPar = list(highestVar = 50),
                     filtSamp = "totalReads",
                     filtSampPar = list(totalReads = 1000),
                     sparsMethod = "none",
                     normMethod = "none",
                     verbose = 3)

# Network analysis (see ?netAnalyze for details)
props1 <- netAnalyze(net1, clustMethod = "cluster_fast_greedy")

# Network plot (see ?plot.microNetProps for details)
plot(props1)

#----------------------------------------------------------------------------
# Same network as before but on genus level and without taxa filtering

amgut.genus.phy <- phyloseq::tax_glom(amgut2.filt.phy, taxrank = "Rank6")

dim(phyloseq::otu_table(amgut.genus.phy))

# Rename taxonomic table and make Rank6 (genus) unique
amgut.genus.renamed <- renameTaxa(amgut.genus.phy, pat = "<name>", 
                                  substPat = "<name>_<subst_name>(<subst_R>)",
                                  numDupli = "Rank6")
                                  
net_genus <- netConstruct(amgut.genus.renamed, 
                          taxRank = "Rank6",
                          measure = "spieceasi",
                          measurePar = list(method = "mb",
                                            pulsar.params = list(rep.num = 10),
                                            symBetaMode = "ave"),
                          filtSamp = "totalReads",
                          filtSampPar = list(totalReads = 1000),
                          sparsMethod = "none",
                          normMethod = "none",
                          verbose = 3)

# Network analysis
props_genus <- netAnalyze(net_genus, clustMethod = "cluster_fast_greedy")

# Network plot (with some modifications)
plot(props_genus, 
     shortenLabels = "none",
     labelScale = FALSE,
     cexLabels = 0.8)

#----------------------------------------------------------------------------
# Single network with the following specifications:
# - Association measure: Pearson correlation
# - Taxa filtering: Keep the 50 taxa with highest frequency
# - Sample filtering: Keep samples with a total number of reads of at least 
#  1000 and with at least 10 taxa with a non-zero count
# - Zero replacement: A pseudo count of 0.5 is added to all counts
# - Normalization: clr transformation
# - Sparsification: Threshold = 0.3 
#  (an edge exists between taxa with an estimated association >= 0.3)

net2 <- netConstruct(amgut2.filt.phy, 
                     measure = "pearson",
                     filtTax = "highestFreq",
                     filtTaxPar = list(highestFreq = 50),
                     filtSamp = c("numbTaxa", "totalReads"),
                     filtSampPar = list(totalReads = 1000, numbTaxa = 10),
                     zeroMethod = "pseudo", 
                     zeroPar = list(pseudocount = 0.5),
                     normMethod = "clr",
                     sparsMethod = "threshold",
                     thresh = 0.3,
                     verbose = 3)

# Network analysis
props2 <- netAnalyze(net2, clustMethod = "cluster_fast_greedy")

plot(props2)

#----------------------------------------------------------------------------
# Constructing and analyzing two networks 
# - A random group variable is used for splitting the data into two groups

set.seed(123456)
group <- sample(1:2, nrow(amgut1.filt), replace = TRUE)

# Option 1: Use the count matrix and group vector as input:
net3 <- netConstruct(amgut1.filt,  
                     group = group,
                     measure = "pearson",
                     filtTax = "highestVar",
                     filtTaxPar = list(highestVar = 50),
                     filtSamp = "totalReads",
                     filtSampPar = list(totalReads = 1000),
                     zeroMethod = "multRepl", 
                     normMethod = "clr",
                     sparsMethod = "t-test")
                     
# Option 2: Pass the count matrix of group 1 to 'data' 
#           and that of group 2 to 'data2'
# Note: Argument 'jointPrepro' is set to FALSE by default (the data sets 
# are filtered separately and the intersect of filtered taxa is kept, 
# which leads to less than 50 taxa in this example).

amgut1 <- amgut1.filt[group == 1, ]
amgut2 <- amgut1.filt[group == 2, ]

net3 <- netConstruct(data = amgut1, 
                     data2 = amgut2,
                     measure = "pearson",
                     filtTax = "highestVar",
                     filtTaxPar = list(highestVar = 50),
                     filtSamp = "totalReads",
                     filtSampPar = list(totalReads = 1000),
                     zeroMethod = "multRepl", 
                     normMethod = "clr",
                     sparsMethod = "t-test")
                           
# Network analysis
# Note: Please zoom into the GCM plot or open a new window using:
# x11(width = 10, height = 10)
props3 <- netAnalyze(net3, clustMethod = "cluster_fast_greedy")

# Network plot (same layout is used in both groups)
plot(props3, sameLayout = TRUE)

# The two networks can be compared with NetCoMi's function netCompare().

#----------------------------------------------------------------------------
# Example of using the argument "assoBoot"

# This functionality is useful for splitting up a large number of bootstrap 
# replicates and run the bootstrapping procedure iteratively.

niter <- 5
nboot <- 1000
# Overall number of bootstrap replicates: 5000

# Use a different seed for each iteration
seeds <- sample.int(1e8, size = niter)

# List where all bootstrap association matrices are stored
assoList <- list()

for (i in 1:niter) {
  # assoBoot is set to TRUE to return the bootstrap association matrices
  net <- netConstruct(amgut1.filt,
                      filtTax = "highestFreq",
                      filtTaxPar = list(highestFreq = 50),
                      filtSamp = "totalReads",
                      filtSampPar = list(totalReads = 0),
                      measure = "pearson",
                      normMethod = "clr",    
                      zeroMethod = "pseudoZO",
                      sparsMethod = "bootstrap",
                      cores = 1,
                      nboot = nboot,
                      assoBoot = TRUE,
                      verbose = 3,
                      seed = seeds[i])
  
  assoList[(1:nboot) + (i - 1) * nboot] <- net$assoBoot1
}

# Construct the actual network with all 5000 bootstrap association matrices
net_final <- netConstruct(amgut1.filt,
                          filtTax = "highestFreq",
                          filtTaxPar = list(highestFreq = 50),
                          filtSamp = "totalReads",
                          filtSampPar = list(totalReads = 0),
                          measure = "pearson",
                          normMethod = "clr",    
                          zeroMethod = "pseudoZO",
                          sparsMethod = "bootstrap",
                          cores = 1,
                          nboot = nboot * niter,
                          assoBoot = assoList,
                          verbose = 3)

# Network analysis
props <- netAnalyze(net_final, clustMethod = "cluster_fast_greedy")

# Network plot
plot(props)

}
\references{
\insertRef{badri2020normalization}{NetCoMi}\cr\cr
  \insertRef{benjamini2000adaptive}{NetCoMi}\cr\cr
  \insertRef{farcomeni2007some}{NetCoMi}\cr\cr
  \insertRef{friedman2012inferring}{NetCoMi} \cr\cr
  \insertRef{WGCNApackage}{NetCoMi}\cr\cr
  \insertRef{zhang2005general}{NetCoMi}
}
\seealso{
\code{\link{netAnalyze}} for analyzing the constructed
  network(s), \code{\link{netCompare}} for network comparison,
  \code{\link{diffnet}} for constructing differential networks.
}
