Type: | Package |
Title: | Flexible Non-Linear Least Square Model Fitting |
Version: | 1.2.0 |
Maintainer: | Johan Aparicio <aparicioarce@wisc.edu> |
Description: | Provides tools for flexible non-linear least squares model fitting using general-purpose optimization techniques. The package supports a variety of optimization algorithms, including those provided by the 'optimx' package, making it suitable for handling complex non-linear models. Features include parallel processing support via the 'future' and 'foreach' packages, comprehensive model diagnostics, and visualization capabilities. Implements methods described in Nash and Varadhan (2011, <doi:10.18637/jss.v043.i09>). |
License: | MIT + file LICENSE |
Encoding: | UTF-8 |
LazyData: | true |
Depends: | R (≥ 4.1) |
RoxygenNote: | 7.3.2 |
Author: | Johan Aparicio [cre, aut], Jeffrey Endelman [aut], University of Wisconsin Madison [cph] |
Imports: | agriutilities, doFuture, dplyr, foreach, future, ggplot2, numDeriv, optimx, progressr, rlang, subplex, tibble, tidyr |
URL: | https://apariciojohan.github.io/flexFitR/, https://github.com/AparicioJohan/flexFitR |
BugReports: | https://github.com/AparicioJohan/flexFitR/issues |
Suggests: | BB, dfoptim, ggpubr, kableExtra, knitr, lbfgsb3c, marqLevAlg, purrr, rmarkdown, ucminf |
VignetteBuilder: | knitr |
NeedsCompilation: | no |
Packaged: | 2025-04-16 16:10:07 UTC; johan |
Repository: | CRAN |
Date/Publication: | 2025-04-16 16:40:08 UTC |
flexFitR: Flexible Non-Linear Least Square Model Fitting
Description
Provides tools for flexible non-linear least squares model fitting using general-purpose optimization techniques. The package supports a variety of optimization algorithms, including those provided by the 'optimx' package, making it suitable for handling complex non-linear models. Features include parallel processing support via the 'future' and 'foreach' packages, comprehensive model diagnostics, and visualization capabilities. Implements methods described in Nash and Varadhan (2011, doi:10.18637/jss.v043.i09).
Author(s)
Maintainer: Johan Aparicio aparicioarce@wisc.edu
Authors:
Jeffrey Endelman endelman@wisc.edu
Other contributors:
University of Wisconsin Madison [copyright holder]
See Also
Useful links:
Report bugs at https://github.com/AparicioJohan/flexFitR/issues
Delta method point estimation
Description
Delta method point estimation
Usage
.delta_method(fit, x_new, se_interval = "confidence")
Arguments
fit |
A fit object which is located inside a modeler object |
x_new |
A vector of x values to evaluate the function. |
se_interval |
A character string. "confidence" or "prediction". |
Value
A data.frame of the evaluated values.
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
print(mod_1)
# Point Prediction
predict(mod_1, x = 45, type = "point", id = 2)
Delta method AUC estimation
Description
Delta method AUC estimation
Usage
.delta_method_auc(fit, x_new, n_points = 1000)
Arguments
fit |
A fit object which is located inside a modeler object |
x_new |
A vector of size 2 given the interval to calculate the area under. |
n_points |
Numeric value giving the number of points to use in the trapezoidal method. |
Value
A data.frame of the evaluated values.
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
print(mod_1)
# AUC Prediction
predict(mod_1, x = c(0, 108), type = "auc", id = 2)
Delta method for derivative estimation
Description
Delta method for derivative estimation
Usage
.delta_method_deriv(fit, x_new, which = "fd")
Arguments
fit |
A fit object which is located inside a modeler object |
x_new |
A vector of x values to evaluate the derivative. |
which |
Can be "fd" for first-derivative or "sd" for second-derivative. |
Value
A data.frame of the evaluated values.
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
print(mod_1)
# First Derivative
predict(mod_1, x = 45, type = "fd", id = 2)
Delta method generic function
Description
Delta method generic function
Usage
.delta_method_gen(fit, formula)
Arguments
fit |
A fit object which is located inside a modeler object |
formula |
A formula specifying a function of the parameters to be estimated (e.g., |
Value
A data.frame of the evaluated formula.
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
print(mod_1)
# Function of the parameters
predict(mod_1, formula = ~ t2 - t1, id = 2)
General-purpose optimization
Description
The function .fitter_curve is used internally to find the parameters requested.
Usage
.fitter_curve(data, id, fn, method, lower, upper, control, metadata, trace)
Arguments
data |
A nested data.frame with columns <plot, genotype, row, range, data, initials, fx_params>. |
id |
An optional vector of IDs to filter the data. Default is |
fn |
A string specifying the name of the function to be used for the curve fitting. Default is |
method |
A character vector specifying the optimization methods to be used. See |
lower |
Numeric vector specifying the lower bounds for the parameters. Default is |
upper |
Numeric vector specifying the upper bounds for the parameters. Default is |
control |
A list of control parameters to be passed to the optimization function. For example, |
trace |
If |
Value
A list containing the following elements:
kkopt
opm object.
param
Data frame with best solution parameters.
rr
Data frame with all methods tested.
details
Additional details of the best solution.
hessian
Hessian matrix.
type
Data frame describing the type of coefficient (estimable of fixed)
conv
Convergency.
p
Number of parameters estimated.
n_obs
Number of observations.
uid
Unique identifier.
fn_name
Name of the curve-fitting function used.
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = GLI,
grp = Plot,
fn = "fn_lin_pl_lin",
parameters = c(t1 = 38.7, t2 = 62, t3 = 90, k = 0.32, beta = -0.01),
subset = 195,
options = list(add_zero = TRUE)
)
Extra Sum-of-Squares F-Test for modeler
objects
Description
Perform an extra sum-of-squares F-test to compare two nested
models of class modeler
. This test assesses whether the additional
parameters in the full model significantly improve the fit compared to the
reduced model.
Usage
## S3 method for class 'modeler'
anova(object, full_model = NULL, ...)
Arguments
object |
An object of class |
full_model |
An optional object of class |
... |
Additional parameters for future functionality. |
Value
A tibble
containing columns with the F-statistic and
corresponding p-values, indicating whether the full model provides a
significantly better fit than the reduced model.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
dt <- data.frame(X = 1:6, Y = c(12, 16, 44, 50, 95, 100))
mo_1 <- modeler(dt, X, Y, fn = "fn_lin", param = c(m = 10, b = -5))
plot(mo_1)
mo_2 <- modeler(dt, X, Y, fn = "fn_quad", param = c(a = 1, b = 10, c = 5))
plot(mo_2)
anova(mo_1, mo_2)
Augment a modeler
object with influence diagnostics
Description
This function computes various influence diagnostics, including
standardized residuals, studentized residuals, and Cook's distance, for an
object of class modeler
.
Usage
augment(x, id = NULL, metadata = TRUE, ...)
Arguments
x |
An object of class |
id |
Optional unique identifier to filter by a specific group. Default is |
metadata |
Logical. If |
... |
Additional parameters for future functionality. |
Value
A tibble containing the following columns:
uid |
Unique identifier for the group. |
fn_name |
Function name associated with the model. |
x |
Predictor variable values. |
y |
Observed response values. |
.fitted |
Fitted values from the model. |
.resid |
Raw residuals (observed - fitted). |
.hat |
Leverage values for each observation. |
.cooksd |
Cook's distance for each observation. |
.std.resid |
Standardized residuals. |
.stud.resid |
Studentized residuals. |
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_logistic",
parameters = c(a = 0.199, t0 = 47.7, k = 100),
subset = 2
)
print(mod_1)
augment(mod_1)
Combine objects of class modeler
Description
Combine objects of class modeler
. Use with caution, some
functions might not work as expected.
Usage
## S3 method for class 'modeler'
c(...)
Arguments
... |
Objects of class |
Value
A modeler
object.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_logistic",
parameters = c(a = 0.199, t0 = 47.7, k = 100),
subset = 1:2
)
mod_2 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 100),
subset = 1:2
)
mod <- c(mod_1, mod_2)
print(mod)
plot(mod, id = 1:2)
Coefficients for an object of class modeler
Description
Extract the estimated coefficients from an object of class modeler
.
Usage
## S3 method for class 'modeler'
coef(object, id = NULL, metadata = FALSE, df = FALSE, ...)
Arguments
object |
An object of class |
id |
An optional unique identifier to filter by a specific group. Default is |
metadata |
Logical. If |
df |
Logical. If |
... |
Additional parameters for future functionality. |
Value
A data.frame
containing the model's estimated coefficients,
standard errors, and optional metadata or degrees of freedom if specified.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
print(mod_1)
coef(mod_1, id = 2)
Compute tangent line(s) from a modeler
object
Description
Computes the slope and intercept of the tangent line(s) to a fitted curve at one or more specified x-values.
Usage
compute_tangent(object, x = NULL, id = NULL)
Arguments
object |
A fitted object of class |
x |
A numeric vector of x-values at which to compute tangent lines. |
id |
Optional vector of |
Value
A tibble with one row per tangent line and the following columns:
-
uid
: unique identifier of the group. -
fn_name
: Name of the fitted function. -
x
: x-value where the tangent line is evaluated. -
y
: Fitted y-value at x. -
slope
: First derivative (slope of tangent) at x. -
intercept
: y-intercept of the tangent line.
Examples
library(flexFitR)
library(ggplot2)
data(dt_potato)
mod <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_logistic",
parameters = c(a = 4, t0 = 40, k = 100),
subset = 2
)
plot(mod)
tl <- compute_tangent(mod, x = c(48.35, 65))
print(tl)
plot(mod) +
geom_abline(
data = tl,
mapping = aes(slope = slope, intercept = intercept),
linetype = 2,
color = "blue"
) +
geom_point(
data = tl,
mapping = aes(x = x, y = y),
shape = 8,
color = "blue",
size = 2
)
Confidence intervals for a modeler object
Description
Extract confidence intervals for the estimated parameters of an
object of class modeler
.
Usage
## S3 method for class 'modeler'
confint(object, parm = NULL, level = 0.95, id = NULL, ...)
Arguments
object |
An object of class |
parm |
A character vector specifying which parameters should have
confidence intervals calculated. If |
level |
A numeric value indicating the confidence level for the intervals. Default is 0.95, corresponding to a 95% confidence interval. |
id |
An optional unique identifier to filter by a specific group.
Default is |
... |
Additional parameters for future functionality. |
Value
A tibble
containing the lower and upper confidence limits for
each specified parameter.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 35, 45)
)
print(mod_1)
confint(mod_1)
Drone-derived data from a potato breeding trial
Description
Canopy and Green Leaf Index for a potato trial arranged in a p-rep design.
Usage
dt_potato
Format
A tibble with 1372 rows and 8 variables:
- Trial
chr trial name
- Plot
dbl denoting the unique plot id
- Row
dbl denoting the row coordinate
- Range
dbl denoting range coordinate
- gid
chr denoting the genotype id
- DAP
dbl denoting Days after planting
- Canopy
dbl Canopy UAV-Derived
- GLI
dbl Green Leaf Index UAV-Derived
Source
UW - Potato Breeding Program
Explore data
Description
Explores data from a data frame in wide format.
Usage
explorer(data, x, y, id, metadata)
Arguments
data |
A |
x |
The name of the column in |
y |
The names of the columns in |
id |
The names of the columns in |
metadata |
The names of the columns in |
Details
This function helps to explore the dataset before being analyzed with modeler()
.
Value
An object of class explorer
, which is a list containing the following elements:
summ_vars
A data.frame containing summary statistics for each trait at each x point, including minimum, mean, median, maximum, standard deviation, coefficient of variation, number of non-missing values, percentage of missing values, and percentage of negative values.
summ_metadata
A data.frame summarizing the metadata.
locals_min_max
A data.frame containing the local minima and maxima of the mean y values over x.
dt_long
A data.frame in long format, with columns for uid, metadata, var, x, and y
metadata
A character vector with the names of the variables to keep across.
Examples
library(flexFitR)
data(dt_potato)
results <- dt_potato |>
explorer(
x = DAP,
y = c(Canopy, GLI),
id = Plot,
metadata = c(gid, Row, Range)
)
names(results)
head(results$summ_vars)
plot(results, label_size = 4, signif = TRUE, n_row = 2)
# New data format
head(results$dt_long)
Function for point estimation
Description
Function for point estimation
Usage
ff(params, x_new, curve, fixed_params = NA)
Arguments
params |
A vector of parameter values. |
x_new |
A vector of x values to evaluate the function. |
curve |
A string. The name of the function used for curve fitting. |
fixed_params |
A vector of fixed parameter values. NA by default. |
Value
A vector of the evaluated values.
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
print(mod_1)
# Point Prediction
predict(mod_1, x = 45, type = "point", id = 2)
Function for AUC estimation
Description
Function for AUC estimation
Usage
ff_auc(params, x_new, curve, fixed_params = NA, n_points = 1000)
Arguments
params |
A vector of parameter values. |
x_new |
A vector of size 2 given the interval to calculate the area under. |
curve |
A string. The name of the function used for curve fitting. |
fixed_params |
A vector of fixed parameter values. NA by default. |
n_points |
Numeric value giving the number of points to use in the trapezoidal method. |
Value
Area under the fitted curve.
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
print(mod_1)
# AUC Prediction
predict(mod_1, x = c(0, 108), type = "auc", id = 2)
Function for derivatives
Description
Function for derivatives
Usage
ff_deriv(params, x_new, curve, fixed_params = NA, which = "fd")
Arguments
params |
A vector of parameter values. |
x_new |
A vector of x values to evaluate the derivative. |
curve |
A string. The name of the function used for curve fitting. |
fixed_params |
A vector of fixed parameter values. NA by default. |
which |
Can be "fd" for first-derivative or "sd" for second-derivative. |
Value
First or second derivative.
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
print(mod_1)
# First Derivative
predict(mod_1, x = 45, type = "fd", id = 2)
Extract fitted values from a modeler
object
Description
Extract fitted values from a modeler
object
Usage
## S3 method for class 'modeler'
fitted(object, ...)
Arguments
object |
An object of class 'modeler' |
... |
Additional parameters for future functionality. |
Value
A numeric vector of fitted values.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
fitted(mod_1)
Super-exponential exponential function
Description
A piecewise function that models an initial exponential phase with quadratic time dependence, followed by a second exponential phase with a different growth rate.
Usage
fn_exp2_exp(t, t1, t2, alpha, beta)
Arguments
t |
A numeric vector of input values (e.g., time). |
t1 |
The onset time of the response. The function is 0 for all values less than |
t2 |
The transition time between the two exponential phases. Must be greater than |
alpha |
The curvature-controlled exponential rate during the first phase ( |
beta |
The exponential growth rate after |
Details
f(t; t_1, t_2, \alpha, \beta) =
\begin{cases}
0 & \text{if } t < t_1 \\
e^{\alpha \cdot (t - t_1)^2} - 1 & \text{if } t_1 \leq t \leq t_2 \\
\left(e^{\alpha \cdot (t_2 - t_1)^2} - 1\right) \cdot e^{\beta \cdot (t - t_2)} & \text{if } t > t_2
\end{cases}
Value
A numeric vector of the same length as t
, representing the function values.
Examples
library(flexFitR)
plot_fn(
fn = "fn_exp2_exp",
params = c(t1 = 35, t2 = 55, alpha = 1 / 600, beta = -1 / 30),
interval = c(0, 108),
n_points = 2000,
auc_label_size = 3,
y_auc_label = 0.15
)
Super-exponential linear function
Description
A piecewise function that models an initial exponential growth phase based on a squared time difference, followed by a linear phase.
Usage
fn_exp2_lin(t, t1, t2, alpha, beta)
Arguments
t |
A numeric vector of input values (e.g., time). |
t1 |
The onset time of the response. The function is 0 for all values less than |
t2 |
The transition time between exponential and linear phases. Must be greater than |
alpha |
The exponential growth rate controlling the curvature of the exponential phase. |
beta |
The slope of the linear phase after |
Details
f(t; t_1, t_2, \alpha, \beta) =
\begin{cases}
0 & \text{if } t < t_1 \\
e^{\alpha \cdot (t - t_1)^2} - 1 & \text{if } t_1 \leq t \leq t_2 \\
\beta \cdot (t - t_2) + \left(e^{\alpha \cdot (t_2 - t_1)^2} - 1\right) & \text{if } t > t_2
\end{cases}
The exponential section rises gradually from 0 at t1
and accelerates
as time increases. The linear section starts at t2
with a value
matching the end of the exponential phase, ensuring continuity but not
necessarily matching the derivative.
Value
A numeric vector of the same length as t
, representing the function values.
Examples
library(flexFitR)
plot_fn(
fn = "fn_exp2_lin",
params = c(t1 = 35, t2 = 55, alpha = 1 / 600, beta = -1 / 80),
interval = c(0, 108),
n_points = 2000,
auc_label_size = 3
)
Double-exponential function
Description
A piecewise function with two exponential phases. The first exponential phase
occurs between t1
and t2
, and the second phase continues after
t2
with a potentially different growth rate. The function ensures
continuity at the transition point but not necessarily smoothness (in derivative).
Usage
fn_exp_exp(t, t1, t2, alpha, beta)
Arguments
t |
A numeric vector of input values (e.g., time). |
t1 |
The onset time of the response. The function is 0 for all values less than |
t2 |
The transition time between the two exponential phases. Must be greater than |
alpha |
The exponential growth rate during the first phase ( |
beta |
The exponential growth rate after |
Details
f(t; t_1, t_2, \alpha, \beta) =
\begin{cases}
0 & \text{if } t < t_1 \\
e^{\alpha \cdot (t - t_1)} - 1 & \text{if } t_1 \leq t \leq t_2 \\
\left(e^{\alpha \cdot (t_2 - t_1)} - 1\right) \cdot e^{\beta \cdot (t - t_2)} & \text{if } t > t_2
\end{cases}
The function rises from 0 starting at t1
with exponential growth rate
alpha
, and transitions to a second exponential phase with rate
beta
at t2
. The value at the transition point is preserved,
ensuring continuity.
Value
A numeric vector of the same length as t
, representing the function values.
Examples
library(flexFitR)
plot_fn(
fn = "fn_exp_exp",
params = c(t1 = 35, t2 = 55, alpha = 1 / 20, beta = -1 / 30),
interval = c(0, 108),
n_points = 2000,
auc_label_size = 3,
y_auc_label = 0.2
)
Exponential-linear function
Description
A piecewise function that models a response with an initial exponential growth phase followed by a linear phase. Commonly used to describe processes with rapid early increases that slow into a linear trend, while maintaining continuity.
Usage
fn_exp_lin(t, t1, t2, alpha, beta)
Arguments
t |
A numeric vector of input values (e.g., time). |
t1 |
The onset time of the response. The function is 0 for all values less than |
t2 |
The transition time between exponential and linear phases. Must be greater than |
alpha |
The exponential growth rate during the exponential phase. |
beta |
The slope of the linear phase after |
Details
f(t; t_1, t_2, \alpha, \beta) =
\begin{cases}
0 & \text{if } t < t_1 \\
e^{\alpha \cdot (t - t_1)} - 1 & \text{if } t_1 \leq t \leq t_2 \\
\beta \cdot (t - t_2) + \left(e^{\alpha \cdot (t_2 - t_1)} - 1\right) & \text{if } t > t_2
\end{cases}
The exponential segment starts from 0 at t1
, and the linear segment
continues smoothly from the end of the exponential part. This ensures value
continuity at t2
, but not necessarily smoothness in slope.
Value
A numeric vector of the same length as t
, representing the function values.
Examples
library(flexFitR)
plot_fn(
fn = "fn_exp_lin",
params = c(t1 = 35, t2 = 55, alpha = 1 / 20, beta = -1 / 40),
interval = c(0, 108),
n_points = 2000,
auc_label_size = 3
)
Linear function
Description
A basic linear function of the form f(t) = m * t + b
, where m
is the slope and b
is the intercept.
Usage
fn_lin(t, m, b)
Arguments
t |
A numeric vector of input values (e.g., time). |
m |
The slope of the line. |
b |
The intercept (function value when |
Details
f(t; m, b) = m \cdot t + b
Value
A numeric vector of the same length as t
, giving the linear function values.
Examples
library(flexFitR)
plot_fn(
fn = "fn_lin",
params = c(m = 2, b = 10),
interval = c(0, 108),
n_points = 2000
)
Linear-logistic function
Description
A piecewise function that models an initial linear increase followed by a logistic saturation.
Usage
fn_lin_logis(t, t1, t2, k)
Arguments
t |
A numeric vector of input values (e.g., time). |
t1 |
The onset time of the response. The function is 0 for all values less than |
t2 |
The transition time between the linear and logistic phases. Must be greater than |
k |
The plateau height. The function transitions toward this value in the logistic phase. |
Details
f(t; t_1, t_2, k) =
\begin{cases}
0 & \text{if } t < t_1 \\
\dfrac{k}{2(t_2 - t_1)} \cdot (t - t_1) & \text{if } t_1 \leq t \leq t_2 \\
\dfrac{k}{1 + e^{-2(t - t_2) / (t_2 - t_1)}} & \text{if } t > t_2
\end{cases}
The linear segment rises from 0 starting at t1
, and the logistic segment begins at t2
,
smoothly approaching the plateau value k
.
Value
A numeric vector of the same length as t
, representing the function values.
Examples
library(flexFitR)
plot_fn(
fn = "fn_lin_logis",
params = c(t1 = 35, t2 = 50, k = 100),
interval = c(0, 108),
n_points = 2000,
auc_label_size = 3
)
Linear plateau linear function
Description
A piecewise function that models an initial linear increase up to a plateau, maintains that plateau for a duration, and then decreases linearly.
Usage
fn_lin_pl_lin(t, t1, t2, t3, k, beta)
Arguments
t |
A numeric vector of input values (e.g., time). |
t1 |
The onset time of the response. The function is 0 for all values less than |
t2 |
The time when the linear growth phase ends and the plateau begins. Must be greater than |
t3 |
The time when the plateau ends and the linear decline begins. Must be greater than |
k |
The height of the plateau. The first linear phase increases to this value, which remains constant until |
beta |
The slope of the final linear phase (typically negative), controlling the rate of decline after |
Details
f(t; t_1, t_2, t_3, k, \beta) =
\begin{cases}
0 & \text{if } t < t_1 \\
\dfrac{k}{t_2 - t_1} \cdot (t - t_1) & \text{if } t_1 \leq t \leq t_2 \\
k & \text{if } t_2 \leq t \leq t_3 \\
k + \beta \cdot (t - t_3) & \text{if } t > t_3
\end{cases}
The function transitions continuously between all three phases but is not
differentiable at the transition points t1
, t2
, and t3
.
Value
A numeric vector of the same length as t
, representing the function values.
Examples
library(flexFitR)
plot_fn(
fn = "fn_lin_pl_lin",
params = c(t1 = 38.7, t2 = 62, t3 = 90, k = 0.32, beta = -0.01),
interval = c(0, 108),
n_points = 2000,
auc_label_size = 3
)
Linear plateau linear with constrains
Description
A piecewise function that models an initial linear increase to a plateau, followed by a specified duration of stability, and then a linear decline. This version parameterizes the plateau using its duration rather than an explicit end time, making it convenient for box type of constraints optimizations.
Usage
fn_lin_pl_lin2(t, t1, t2, dt, k, beta)
Arguments
t |
A numeric vector of input values (e.g., time). |
t1 |
The onset time of the response. The function is 0 for all values less than |
t2 |
The time when the linear growth phase ends and the plateau begins. Must be greater than |
dt |
The duration of the plateau phase. The plateau ends at |
k |
The height of the plateau. The linear phase increases to this value, which remains constant for |
beta |
The slope of the decline phase that begins after the plateau. Typically negative. |
Details
f(t; t_1, t_2, dt, k, \beta) =
\begin{cases}
0 & \text{if } t < t_1 \\
\dfrac{k}{t_2 - t_1} \cdot (t - t_1) & \text{if } t_1 \leq t \leq t_2 \\
k & \text{if } t_2 \leq t \leq (t_2 + dt) \\
k + \beta \cdot (t - (t_2 + dt)) & \text{if } t > (t_2 + dt)
\end{cases}
Value
A numeric vector of the same length as t
, representing the function values.
Examples
library(flexFitR)
plot_fn(
fn = "fn_lin_pl_lin2",
params = c(t1 = 38.7, t2 = 62, dt = 28, k = 0.32, beta = -0.01),
interval = c(0, 108),
n_points = 2000,
auc_label_size = 3
)
Linear plateau function
Description
A simple piecewise function that models a linear increase from zero to a plateau. The function rises linearly between two time points and then levels off at a constant value.
Usage
fn_lin_plat(t, t1 = 45, t2 = 80, k = 0.9)
Arguments
t |
A numeric vector of input values (e.g., time). |
t1 |
The onset time of the response. The function is 0 for all values less than |
t2 |
The time at which the plateau begins. Must be greater than |
k |
The height of the plateau. The function linearly increases from
0 to |
Details
f(t; t_1, t_2, k) =
\begin{cases}
0 & \text{if } t < t_1 \\
\dfrac{k}{t_2 - t_1} \cdot (t - t_1) & \text{if } t_1 \leq t \leq t_2 \\
k & \text{if } t > t_2
\end{cases}
This function is continuous but not differentiable at t1
and t2
due to the piecewise transitions. It is often used in agronomy and ecology
to describe growth until a resource limit or developmental plateau is reached.
Value
A numeric vector of the same length as t
, representing the function values.
Examples
library(flexFitR)
plot_fn(
fn = "fn_lin_plat",
params = c(t1 = 34.9, t2 = 61.8, k = 100),
interval = c(0, 108),
n_points = 2000,
auc_label_size = 3
)
Logistic function
Description
A standard logistic function commonly used to model sigmoidal growth. The
curve rises from near zero to a maximum value k
, with inflection point
at t0
and growth rate a
.
Usage
fn_logistic(t, a, t0, k)
Arguments
t |
A numeric vector of input values (e.g., time). |
a |
The growth rate (steepness of the curve). Higher values lead to a steeper rise. |
t0 |
The time of the inflection point (midpoint of the transition). |
k |
The upper asymptote or plateau (maximum value as |
Details
f(t; a, t0, k) = \frac{k}{1 + e^{-a(t - t_0)}}
This is a classic sigmoid (S-shaped) curve that is symmetric around the
inflection point t0
.
Value
A numeric vector of the same length as t
, representing the logistic function values.
Examples
library(flexFitR)
plot_fn(
fn = "fn_logistic",
params = c(a = 0.199, t0 = 47.7, k = 100),
interval = c(0, 108),
n_points = 2000
)
Quadratic function
Description
A standard quadratic function of the form f(t) = a * t^2 + b * t + c
, where
a
controls curvature, b
is the linear coefficient, and c
is the intercept.
Usage
fn_quad(t, a, b, c)
Arguments
t |
A numeric vector of input values (e.g., time). |
a |
The quadratic coefficient (curvature). |
b |
The linear coefficient (slope at the origin). |
c |
The intercept (function value when |
Details
f(t; a, b, c) = a \cdot t^2 + b \cdot t + c
This function represents a second-degree polynomial. The sign of a
determines whether the parabola opens upward (a > 0
) or downward (a < 0
).
Value
A numeric vector of the same length as t
, representing the
quadratic function values.
Examples
library(flexFitR)
plot_fn(fn = "fn_quad", params = c(a = 1, b = 10, c = 5))
Smooth Quadratic-plateau function
Description
A piecewise function that models a quadratic increase from zero to a plateau value. The function is continuous and differentiable, modeling growth processes with a smooth transition to a maximum response.
Usage
fn_quad_pl_sm(t, t1, t2, k)
Arguments
t |
A numeric vector of input values (e.g., time). |
t1 |
The onset time of the response. The function is 0 for all values less than |
t2 |
The time at which the plateau begins. Must be greater than |
k |
The plateau height. The function transitions to this constant value at |
Details
f(t; t_1, t_2, k) =
\begin{cases}
0 & \text{if } t < t_1 \\
-\dfrac{k}{(t_2 - t_1)^2} (t - t_1)^2 + \dfrac{2k}{t_2 - t_1} (t - t_1) & \text{if } t_1 \leq t \leq t_2 \\
k & \text{if } t > t_2
\end{cases}
The coefficients of the quadratic section are chosen such that the curve passes through
(t1, 0)
and (t2, k)
with a continuous first derivative (i.e., smooth transition).
Value
A numeric vector of the same length as t
, representing the function values.
Examples
library(flexFitR)
plot_fn(
fn = "fn_quad_pl_sm",
params = c(t1 = 35, t2 = 80, k = 100),
interval = c(0, 108),
n_points = 2000,
auc_label_size = 3
)
Quadratic-plateau function
Description
Computes a value based on a quadratic-plateau growth curve.
Usage
fn_quad_plat(t, t1 = 45, t2 = 80, b = 1, k = 100)
Arguments
t |
A numeric vector of input values (e.g., time). |
t1 |
The onset time of the response. The function is 0 for all values less than |
t2 |
The time at which the plateau begins. Must be greater than |
b |
The initial slope of the curve at |
k |
The plateau height. The function transitions to this constant value at |
Details
f(t; t_1, t_2, b, k) =
\begin{cases}
0 & \text{if } t < t_1 \\
b (t - t_1) + \frac{k - b (t_2 - t_1)}{(t_2 - t_1)^2} (t - t_1)^2 & \text{if } t_1 \leq t \leq t_2 \\
k & \text{if } t > t_2
\end{cases}
This function allows the user to specify the initial slope b
. The curvature term
is automatically calculated so that the function reaches the plateau value k
exactly
at t2
. The transition to the plateau is continuous in value but not necessarily smooth
in derivative.
Value
A numeric vector of the same length as t
, representing the function values.
Examples
library(flexFitR)
plot_fn(
fn = "fn_quad_plat",
params = c(t1 = 35, t2 = 80, b = 4, k = 100),
interval = c(0, 108),
n_points = 2000,
auc_label_size = 3
)
Akaike's An Information Criterion for an object of class modeler
Description
Generic function calculating Akaike's ‘An Information Criterion’
for fitted model object of class modeler
.
Usage
## S3 method for class 'modeler'
AIC(object, ..., k = 2)
## S3 method for class 'modeler'
BIC(object, ...)
Arguments
object |
An object inheriting from class |
... |
Further parameters. For future improvements. |
k |
Numeric, the penalty per parameter to be used; the default k = 2 is the classical AIC. |
Value
A tibble
with columns giving the corresponding AIC and BIC.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
dt <- data.frame(X = 1:6, Y = c(12, 16, 44, 50, 95, 100))
mo_1 <- modeler(dt, X, Y, fn = "fn_lin", param = c(m = 10, b = -5))
mo_2 <- modeler(dt, X, Y, fn = "fn_quad", param = c(a = 1, b = 10, c = 5))
AIC(mo_1)
AIC(mo_2)
BIC(mo_1)
BIC(mo_2)
Generic for inverse prediction
Description
Generic for inverse prediction
Usage
inverse_predict(object, ...)
Arguments
object |
An object for which to compute the inverse prediction. |
... |
Additional arguments passed to methods. |
Inverse prediction from a modeler
object
Description
Computes the x-value at which a fitted model reaches a user-specified response value (y-value).
Usage
## S3 method for class 'modeler'
inverse_predict(
object,
y,
id = NULL,
interval = NULL,
tol = 1e-06,
resolution = 1000,
...
)
Arguments
object |
A fitted object of class |
y |
A numeric scalar giving the target y-value for which to compute the corresponding x. |
id |
Optional vector of |
interval |
Optional numeric vector of length 2 specifying the interval in which to search for the root.
If |
tol |
Numerical tolerance passed to |
resolution |
Integer. Number of grid points used to scan the interval. |
... |
Additional parameters for future functionality. |
Details
The function uses numeric root-finding to solve f(t, ...params) = y
.
If no root is found in the interval, NA
is returned.
Value
A tibble
with one row per group, containing:
-
uid
– unique identifier of the group, -
fn_name
– the name of the fitted function, -
lower
andupper
– the search interval used, -
y
– the predicted y-value (from the function at the root), -
x
– the x-value at which the function reachesy
.
See Also
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
print(mod_1)
inverse_predict(mod_1, y = 50)
inverse_predict(mod_1, y = 75, interval = c(20, 80))
Print available functions in flexFitR
Description
Print available functions in flexFitR
Usage
list_funs()
Value
A vector with available functions
Examples
library(flexFitR)
list_funs()
Print available methods in flexFitR
Description
Print available methods in flexFitR
Usage
list_methods(bounds = FALSE, check_package = FALSE)
Arguments
bounds |
If TRUE, returns methods for box (or bounds) constraints. FALSE by default. |
check_package |
If TRUE, ensures solvers are installed. FALSE by default. |
Value
A vector with available methods
Examples
library(flexFitR)
list_methods()
Extract Log-Likelihood for an object of class modeler
Description
logLik for an object of class modeler
Usage
## S3 method for class 'modeler'
logLik(object, ...)
Arguments
object |
An object inheriting from class |
... |
Further parameters. For future improvements. |
Value
A tibble
with the Log-Likelihood for the fitted models.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
dt <- data.frame(X = 1:6, Y = c(12, 16, 44, 50, 95, 100))
mo_1 <- modeler(dt, X, Y, fn = "fn_lin", param = c(m = 10, b = -5))
plot(mo_1)
logLik(mo_1)
Metrics for an object of class modeler
Description
Computes various performance metrics for a modeler object. The function calculates Sum of Squared Errors (SSE), Mean Absolute Error (MAE), Mean Squared Error (MSE), Root Mean Squared Error (RMSE), and the Coefficient of Determination (R-squared).
Usage
metrics(x, by_grp = TRUE)
Arguments
x |
An object of class 'modeler' containing the necessary data to compute the metrics. |
by_grp |
Return the metrics by id? TRUE by default. |
Details
Sum of Squared Errors (SSE):
SSE = \sum_{i=1}^{n} (y_i - \hat{y}_i)^2
Mean Absolute Error (MAE):
MAE = \frac{1}{n} \sum_{i=1}^{n} |y_i - \hat{y}_i|
Mean Squared Error (MSE):
MSE = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2
Root Mean Squared Error (RMSE):
RMSE = \sqrt{\frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2}
Coefficient of Determination (R-squared):
R^2 = 1 - \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{\sum_{i=1}^{n} (y_i - \bar{y})^2}
Value
A data frame containing the calculated metrics grouped by uid, metadata, and variables.
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(1:2)
)
plot(mod_1, id = c(1:2))
print(mod_1)
metrics(mod_1)
Modeler: Non-linear regression for curve fitting
Description
A versatile function for performing non-linear least squares optimization on grouped data. It supports customizable optimization methods, flexible initial/fixed parameters, and parallel processing.
Usage
modeler(
data,
x,
y,
grp,
keep,
fn = "fn_lin_plat",
parameters = NULL,
lower = -Inf,
upper = Inf,
fixed_params = NULL,
method = c("subplex", "pracmanm", "anms"),
subset = NULL,
options = modeler.options(),
control = list()
)
Arguments
data |
A |
x |
The name of the column in |
y |
The name of the column in |
grp |
Column(s) in |
keep |
Names of columns to retain in the output. Defaults to |
fn |
A string. The name of the function used for curve fitting.
Example: |
parameters |
A numeric vector, named list, or
Defaults to |
lower |
A numeric vector specifying lower bounds for parameters. Defaults to |
upper |
A numeric vector specifying upper bounds for parameters. Defaults to |
fixed_params |
A list or
Defaults to |
method |
A character vector specifying optimization methods.
Check available methods using |
subset |
A vector (optional) containing levels of |
options |
A list of additional options. See
|
control |
A list of control parameters to be passed to the optimization function. For example: |
Value
An object of class modeler
, which is a list containing the following elements:
param
Data frame containing optimized parameters and related information.
dt
Data frame with input data, fitted values, and residuals.
metrics
Metrics and summary of the models.
execution
Total execution time for the analysis.
response
Name of the response variable analyzed.
keep
Metadata retained based on the
keep
argument.fun
Name of the curve-fitting function used.
parallel
List containing parallel execution details (if applicable).
fit
List of fitted models for each group.
Examples
library(flexFitR)
data(dt_potato)
explorer <- explorer(dt_potato, x = DAP, y = c(Canopy, GLI), id = Plot)
# Example 1
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = GLI,
grp = Plot,
fn = "fn_lin_pl_lin",
parameters = c(t1 = 38.7, t2 = 62, t3 = 90, k = 0.32, beta = -0.01),
subset = 195
)
plot(mod_1, id = 195)
print(mod_1)
# Example 2
mod_2 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = 195
)
plot(mod_2, id = 195)
print(mod_2)
Compare performance of different models
Description
Computes indices of model performance for different models at once and hence allows comparison of indices across models.
Usage
performance(..., metrics = "all", metadata = FALSE, digits = 2)
Arguments
... |
Multiple model objects (only of class 'modeler'). |
metrics |
Can be "all" or a character vector of metrics to be computed (one or more of "logLik", "AIC", "AICc", "BIC", "Sigma", "SSE", "MAE", "MSE", "RMSE", "R2"). "all" by default. |
metadata |
Logical. If |
digits |
An integer. The number of decimal places to round the output. Default is 2. |
Value
A data.frame with performance metrics for models in (...).
Examples
library(flexFitR)
data(dt_potato)
# Model 1
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 90),
subset = 40
)
print(mod_1)
# Model 2
mod_2 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_logistic",
parameters = c(a = 0.199, t0 = 47.7, k = 100),
subset = 40
)
print(mod_2)
# Model 3
mod_3 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin",
parameters = c(m = 20, b = 2),
subset = 40
)
print(mod_3)
performance(mod_1, mod_2, mod_3, metrics = c("AIC", "AICc", "BIC", "Sigma"))
Plot an object of class explorer
Description
Creates various plots for an object of class explorer
.
Depending on the specified type, the function can generate plots that show correlations between variables over x, correlations between x values for each variable, or the evolution of variables over x.
Usage
## S3 method for class 'explorer'
plot(
x,
type = "var_by_x",
label_size = 4,
signif = FALSE,
method = "pearson",
filter_var = NULL,
id = NULL,
n_row = NULL,
n_col = NULL,
base_size = 13,
return_gg = FALSE,
add_avg = FALSE,
...
)
Arguments
x |
An object inheriting from class |
type |
Character string or number specifying the type of plot to generate. Available options are:
|
label_size |
Numeric. Size of the labels in the plot. Default is 4. Only works with type 1 and 2. |
signif |
Logical. If |
method |
Character string specifying the method for correlation calculation. Available options are |
filter_var |
Character vector specifying the variables to exclude from the plot. |
id |
Optional unique identifier to filter the evolution type of plot. Default is |
n_row |
Integer specifying the number of rows to use in |
n_col |
Integer specifying the number of columns to use in |
base_size |
Numeric. Base font size for the plot. Default is 13. |
return_gg |
Logical. If |
add_avg |
Logical. If |
... |
Further graphical parameters for future improvements. |
Value
A ggplot object and an invisible data.frame containing the correlation table when type
is "var_by_x"
or "x_by_var"
.
Examples
library(flexFitR)
data(dt_potato)
results <- explorer(dt_potato, x = DAP, y = c(Canopy, GLI), id = Plot)
table <- plot(results, label_size = 4, signif = TRUE, n_row = 2)
table
plot(results, type = "x_by_var", label_size = 4, signif = TRUE)
Plot an object of class modeler
Description
Creates several plots for an object of class modeler
.
Usage
## S3 method for class 'modeler'
plot(
x,
id = NULL,
type = 1,
label_size = 4,
base_size = 14,
linewidth = 0.5,
color = "red",
color_points = "black",
parm = NULL,
n_points = 1000,
title = NULL,
add_points = FALSE,
add_ci = TRUE,
color_ci = "blue",
color_pi = "red",
add_ribbon_ci = FALSE,
add_ribbon_pi = FALSE,
color_ribbon_ci = "blue",
color_ribbon_pi = "red",
...
)
Arguments
x |
An object of class |
id |
An optional group ID to filter the data for plotting, useful for avoiding overcrowded plots. |
type |
Numeric value (1-6) to specify the type of plot to generate. Default is 1.
|
label_size |
Numeric value for the size of labels. Default is 4. |
base_size |
Numeric value for the base font size in pts. Default is 14. |
linewidth |
Numeric value specifying size of line geoms. Default is 0.5. |
color |
Character string specifying the color for the fitted line when |
color_points |
Character string specifying the color for the raw data points when |
parm |
Character vector specifying the parameters to plot for |
n_points |
Numeric value specifying the number of points for interpolation along the x-axis. Default is 2000. |
title |
Optional character string to add a title to the plot. |
add_points |
Logical value indicating whether to add raw observations to the plot for |
add_ci |
Logical value indicating whether to add confidence intervals for |
color_ci |
Character string specifying the color of the confidence interval when |
color_pi |
Character string specifying the color of the prediction interval when |
add_ribbon_ci |
Logical value indicating whether to add a ribbon for confidence intervals in |
add_ribbon_pi |
Logical value indicating whether to add a ribbon for prediction intervals in |
color_ribbon_ci |
Character string specifying the color of the ribbon (ci). Default is "blue". |
color_ribbon_pi |
Character string specifying the color of the ribbon (pi). Default is "red". |
... |
Additional graphical parameters for future extensions. |
Value
A ggplot
object representing the specified plot.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
data(dt_potato)
# Example 1
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(1:3)
)
print(mod_1)
plot(mod_1, id = 1:2)
plot(mod_1, id = 1:3, type = 2, label_size = 10)
Plot an object of class performance
Description
Creates plots for an object of class performance
Usage
## S3 method for class 'performance'
plot(
x,
id = NULL,
type = 1,
rescale = FALSE,
linewidth = 1,
base_size = 12,
return_table = FALSE,
...
)
Arguments
x |
An object of class |
id |
An optional group ID to filter the data for plotting, useful for avoiding overcrowded plots. This argument is not used when type = 2. |
type |
Numeric value (1-3) to specify the type of plot to generate. Default is 1.
|
rescale |
Logical. If |
linewidth |
Numeric value specifying size of line geoms. |
base_size |
Numeric value for the base font size in pts. Default is 12 |
return_table |
Logical. If |
... |
Additional graphical parameters for future extensions. |
Value
A ggplot
object representing the specified plot.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
data(dt_potato)
# Model 1
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 90),
subset = 40
)
# Model 2
mod_2 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_logistic",
parameters = c(a = 0.199, t0 = 47.7, k = 100),
subset = 40
)
# Model 3
mod_3 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin",
parameters = c(m = 20, b = 2),
subset = 40
)
plot(performance(mod_1, mod_2, mod_3), type = 1)
plot(performance(mod_1, mod_2, mod_3, metrics = c("AICc", "BIC")), type = 3)
Plot user-defined function
Description
This function plots a function over a specified interval and annotates the plot with the calculated Area Under the Curve (AUC) and parameter values. The aim of 'plot_fn' is to allow users to play with different starting values in their functions before fitting any models.
Usage
plot_fn(
fn = "fn_lin_plat",
params = c(t1 = 34.9, t2 = 61.8, k = 100),
interval = c(0, 100),
n_points = 1000,
auc = FALSE,
x_auc_label = NULL,
y_auc_label = NULL,
auc_label_size = 4,
param_label_size = 4,
base_size = 12,
color = "red",
label_color = "grey30"
)
Arguments
fn |
A character string representing the name of the function to be plotted. Default is "fn_lin_plat". |
params |
A named numeric vector of parameters to be passed to the function. Default is |
interval |
A numeric vector of length 2 specifying the interval over which the function is to be plotted. Default is |
n_points |
An integer specifying the number of points to be used for plotting. Default is 1000. |
auc |
Print AUC in the plot? Default is |
x_auc_label |
A numeric value specifying the x-coordinate for the AUC label. Default is |
y_auc_label |
A numeric value specifying the y-coordinate for the AUC label. Default is |
auc_label_size |
A numeric value specifying the size of the AUC label text. Default is 3. |
param_label_size |
A numeric value specifying the size of the parameter label text. Default is 3. |
base_size |
A numeric value specifying the base size for the plot's theme. Default is 12. |
color |
A character string specifying the color for the plot lines and area fill. Default is "red". |
label_color |
A character string specifying the color for the labels. Default is "grey30". |
Value
A ggplot object representing the plot.
Examples
# Example usage
plot_fn(
fn = "fn_lin_plat",
params = c(t1 = 34.9, t2 = 61.8, k = 100),
interval = c(0, 100),
n_points = 1000
)
plot_fn(
fn = "fn_lin_pl_lin",
params <- c(t1 = 38.7, t2 = 62, t3 = 90, k = 0.32, beta = -0.01),
interval = c(0, 100),
n_points = 1000,
base_size = 12
)
Predict an object of class modeler
Description
Generate model predictions from an object of class modeler
.
This function allows for flexible prediction types, including point predictions,
area under the curve (AUC), first or second order derivatives, and functions
of the parameters.
Usage
## S3 method for class 'modeler'
predict(
object,
x = NULL,
id = NULL,
type = c("point", "auc", "fd", "sd"),
se_interval = c("confidence", "prediction"),
n_points = 1000,
formula = NULL,
metadata = FALSE,
parallel = FALSE,
workers = NULL,
...
)
Arguments
object |
An object of class |
x |
A numeric value or vector specifying the points at which predictions
are made. For |
id |
Optional unique identifier to filter predictions by a specific group. Default is |
type |
A character string specifying the type of prediction. Default is "point".
|
se_interval |
A character string specifying the type of interval for
standard error calculation. Options are |
n_points |
An integer specifying the number of points used to approximate
the area under the curve (AUC) when |
formula |
A formula specifying a function of the parameters to be estimated (e.g., |
metadata |
Logical. If |
parallel |
Logical. If |
workers |
The number of parallel processes to use. |
... |
Additional parameters for future functionality. |
Value
A data.frame
containing the predicted values,
their associated standard errors, and optionally the metadata.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
print(mod_1)
# Point Prediction
predict(mod_1, x = 45, type = "point", id = 2)
# AUC Prediction
predict(mod_1, x = c(0, 108), type = "auc", id = 2)
# First Derivative
predict(mod_1, x = 45, type = "fd", id = 2)
# Second Derivative
predict(mod_1, x = 45, type = "sd", id = 2)
# Function of the parameters
predict(mod_1, formula = ~ t2 - t1, id = 2)
Print an object of class modeler
Description
Prints information about modeler
function.
Usage
## S3 method for class 'modeler'
print(x, ...)
Arguments
x |
An object fitted with the function |
... |
Options used by the tibble package to format the output. See 'tibble::print()' for more details. |
Value
an object inheriting from class modeler
.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(1:5)
)
plot(mod_1, id = c(1:4))
print(mod_1)
Extract residuals from a modeler
object
Description
Extract residuals from a modeler
object
Usage
## S3 method for class 'modeler'
residuals(object, ...)
Arguments
object |
An object of class 'modeler' |
... |
Additional parameters for future functionality. |
Value
A numeric vector of residuals
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
residuals(mod_1)
Transform variables in a data frame
Description
This function performs transformations on specified columns of a data frame, including truncating maximum values, handling negative values, and adding a zero to the series. It allows for grouping and supports retaining metadata in the output.
Usage
series_mutate(
data,
x,
y,
grp,
metadata,
max_as_last = FALSE,
check_negative = FALSE,
add_zero = FALSE,
interval = NULL
)
Arguments
data |
A |
x |
The name of the column in |
y |
The name of the column(s) in |
grp |
Column(s) in |
metadata |
Names of columns to retain in the output. Defaults to |
max_as_last |
Logical. If |
check_negative |
Logical. If |
add_zero |
Logical. If |
interval |
A numeric vector of length 2 (start and end) specifying the range to filter the data. Defaults to |
Value
A transformed data.frame
with the specified modifications applied.
Examples
data(dt_potato)
new_data <- series_mutate(
data = dt_potato,
x = DAP,
y = GLI,
grp = gid,
max_as_last = TRUE,
check_negative = TRUE
)
Subset an object of class modeler
Description
Subset an object of class modeler
Usage
## S3 method for class 'modeler'
subset(x, id = NULL, ...)
Arguments
x |
An object of class |
id |
Unique identifier to filter a |
... |
Additional parameters for future functionality. |
Value
A modeler
object.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
data(dt_potato)
mod <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_logistic",
parameters = c(a = 0.199, t0 = 47.7, k = 100),
subset = 1:2
)
print(mod)
mod_new <- subset(mod, id = 2)
print(mod_new)
Update a modeler
object
Description
It creates a new fitted object using the parameter values from the current model as initial values. It can also be used to perform a few additional iterations of a model that has not converged.
Usage
## S3 method for class 'modeler'
update(object, method = NULL, track = TRUE, eps = 1e-06, ...)
Arguments
object |
An object of class |
method |
A character vector specifying optimization methods.
Check available methods using |
track |
Logical. If |
eps |
Numeric. The minimum change in SSE required to consider a fit improved.
Defaults to |
... |
Additional parameters for future functionality. |
Value
An object of class modeler
, which is a list containing the following elements:
param
Data frame containing optimized parameters and related information.
dt
Data frame with input data, fitted values, and residuals.
metrics
Metrics and summary of the models.
execution
Total execution time for the analysis.
response
Name of the response variable analyzed.
keep
Metadata retained based on the
keep
argument.fun
Name of the curve-fitting function used.
parallel
List containing parallel execution details (if applicable).
fit
List of fitted models for each group.
Examples
library(flexFitR)
data(dt_potato)
mo_1 <- dt_potato |>
modeler(
x = DAP,
y = GLI,
grp = Plot,
fn = "fn_lin_pl_lin",
parameters = c(t1 = 10, t2 = 62, t3 = 90, k = 0.32, beta = -0.01),
subset = 195
)
plot(mo_1)
mo_2 <- update(mo_1)
plot(mo_2)
Variance-Covariance matrix for an object of class modeler
Description
Extract the variance-covariance matrix for the parameter estimates
from an object of class modeler
.
Usage
## S3 method for class 'modeler'
vcov(object, id = NULL, ...)
Arguments
object |
An object of class |
id |
An optional unique identifier to filter by a specific group.
Default is |
... |
Additional parameters for future functionality. |
Value
A list of matrices, where each matrix represents the variance-covariance matrix of the estimated parameters for each group or fit.
Author(s)
Johan Aparicio [aut]
Examples
library(flexFitR)
data(dt_potato)
mod_1 <- dt_potato |>
modeler(
x = DAP,
y = Canopy,
grp = Plot,
fn = "fn_lin_plat",
parameters = c(t1 = 45, t2 = 80, k = 0.9),
subset = c(15, 2, 45)
)
print(mod_1)
vcov(mod_1)