| Type: | Package |
| Title: | Insect Ecology Data Analysis Toolkit |
| Version: | 1.1.1 |
| Description: | A collection of analytical tools for insect ecology research, currently covering age-stage, two-sex life table analysis, dose-response bioassays, temperature-dependent development and insect phenology prediction. The life table module follows the age-stage, two-sex life table theory of Chi (1988) <doi:10.1093/ee/17.1.26> and Chi et al. (2020) <doi:10.1127/entomologia/2020/0936>. It supports fast batch processing of multi-group datasets, validates raw 'csv' data, computes cohort size, mean fecundity, age-stage survival rates, age-specific survival, age-specific fecundity, life expectancy, and derived population parameters (net reproductive rate, intrinsic and finite rates of increase, mean generation time), simultaneously generates age-stage survival curves for all groups, and exports all tabular results and plots to 'Excel' in a single run. The bioassay module estimates lethal concentrations by the traditional and the weighted (improved) linear regression methods and by probit analysis (Bliss, 1934) <doi:10.1126/science.79.2037.38>, with the control-mortality correction of Abbott (1925) <doi:10.1093/jee/18.2.265a>, 95% confidence intervals and chi-square goodness-of-fit tests; the lethal proportion can be set freely (e.g., 25%, 50%, 70% or 90%), so any LC value such as the LC25, LC70 or LC90 can be computed, not only the LC50. The regression plots and tables are exported to 'Excel'. The degree-day module estimates the developmental threshold temperature and the effective accumulated temperature by the linear degree-day method (Campbell et al., 1974) <doi:10.2307/2402197>, and fits the common nonlinear temperature- dependent development models following Logan et al. (1976) <doi:10.1093/ee/5.6.1133> (Logan-6), Lactin et al. (1995) <doi:10.1093/ee/24.1.68> and Briere et al. (1999) <doi:10.1093/ee/28.1.22>, plus a 7-parameter Wang model; it selects the best model by AICc, predicts durations and accumulates field degree-days. The emergence module applies the stage-grading method to a single survey of the population stage structure, i.e. to stage-frequency data (Kiritani and Nakasuji, 1967) <doi:10.1007/bf02514921> and Manly (1974) <doi:10.1007/bf00345751>, and projects the beginning, peak and end of the adult emergence period (the 16%, 50% and 84% quantiles), optionally shifting the eclosion dates by the pre-oviposition period and the egg duration to forecast larval hatch. Further extensions, such as median lethal temperature/time (LT50), are planned. |
| License: | MIT + file LICENSE |
| Encoding: | UTF-8 |
| Imports: | dplyr, ggplot2 (≥ 3.5.0), grid, magrittr, openxlsx, ragg, scales, sysfonts, readr, showtext, tidyr, utils |
| Config/roxygen2/version: | 8.1.0 |
| Suggests: | readxl, testthat (≥ 3.0.0), writexl |
| Config/testthat/edition: | 3 |
| URL: | https://github.com/SeaGhost-0/insectecol |
| BugReports: | https://github.com/SeaGhost-0/insectecol/issues |
| Depends: | R (≥ 3.5) |
| NeedsCompilation: | no |
| Packaged: | 2026-10-05 12:13:25 UTC; SeaGhost |
| Author: | Wangyao Li [aut, cre, cph], Yongsheng Zhang [aut], Huan Yu [aut] |
| Maintainer: | Wangyao Li <1561941342@qq.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-10-05 12:40:02 UTC |
Mean Fecundity F
Description
The mean fecundity of the females of the cohort: the total number of
eggs laid by all females divided by the number of females,
F = (total number of eggs) / (number of females).
Usage
calc_F(lt)
Arguments
lt |
A |
Value
A single numeric value: the mean number of eggs per female.
See Also
calc_fxj for the age-specific fecundity.
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
calc_F(lt)
Cohort Size N
Description
The number of individuals in the raw data set, i.e. the number of newly hatched eggs with which the cohort started. All survival rates of the age-stage, two-sex life table are expressed as proportions of this cohort size.
Usage
calc_N(lt)
Arguments
lt |
A |
Value
A single numeric value: the number of data rows.
References
Chi, H. (1988) Life-table analysis incorporating both sexes and variable development rates among individuals. Environmental Entomology 17(1), 26-34.
See Also
lifeTable_calculate_all computes all parameters at once.
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
calc_N(lt)
Net Reproductive Rate R0
Description
The net reproductive rate: the expected number of eggs produced by an
average individual of the cohort over its whole life,
R0 = sum over x of s_x,Female * F_xj. A population with
R0 = 1 exactly replaces itself; R0 > 1 indicates growth
and R0 < 1 decline.
Usage
calc_R0(lt, sxj = NULL, fxj = NULL)
Arguments
lt |
A |
sxj |
Optional; the result of |
fxj |
Optional; the result of |
Value
A single numeric value: the net reproductive rate R0.
References
Goodman, D. (1982) Optimal life histories, optimal notation, and the value of reproductive value. The American Naturalist 119(6), 803-823.
See Also
calc_T, lifeTable_calculate_all
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
calc_R0(lt)
Mean Generation Time T
Description
The mean generation time, calculated as T = log(R0) / r: the
time needed for the population to grow to an R0-fold of its
current size when increasing at the constant rate r.
Usage
calc_T(lt, R0 = NULL, r = NULL)
Arguments
lt |
A |
R0 |
Optional; the result of |
r |
Optional; the result of |
Value
A single numeric value: the mean generation time T (days).
References
Goodman, D. (1982) Optimal life histories, optimal notation, and the value of reproductive value. The American Naturalist 119(6), 803-823.
See Also
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
calc_T(lt)
Life Expectancy e_x
Description
The life expectancy of the individuals that have reached age x,
calculated as the cumulative sum of the age-specific survival rates
from age x to the end of the life table,
e_x = sum over y >= x of l_y.
Usage
calc_ex(lt, lx = NULL)
Arguments
lt |
A |
lx |
Optional; the result of |
Value
A data frame with the columns Age and e_x; one
row per age class.
References
Chi, H. and Liu, H. (1985) Two new methods for the study of insect population ecology. Bulletin of the Institute of Zoology, Academia Sinica 24(2), 225-240.
See Also
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
head(calc_ex(lt))
Age-Specific Female Fecundity F_xj
Description
The mean number of eggs laid per living female at age x. For every female the daily egg counts are aligned to her age at emergence, so that eggs are attributed to the correct age class; the mean is taken over the females still alive at each age.
Usage
calc_fxj(lt, sxj = NULL)
Arguments
lt |
A |
sxj |
Optional; the result of |
Value
A data frame with the columns Age and F_xj; a
terminal row with F_xj = 0 is appended.
See Also
calc_F for the overall mean fecundity,
calc_mx for the age-specific fecundity of the cohort.
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
head(calc_fxj(lt))
Finite Rate of Increase lambda
Description
The finite rate of increase: the multiplication factor of the
population per unit time (day), lambda = exp(r). The population
grows when lambda > 1, stays constant at lambda = 1 and
declines when lambda < 1.
Usage
calc_lambda(lt, r = NULL)
Arguments
lt |
A |
r |
Optional; the result of |
Value
A single numeric value: the finite rate of increase lambda.
References
Birch, L. C. (1948) The intrinsic rate of natural increase of an insect population. Journal of Animal Ecology 17(1), 15-26.
See Also
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
calc_lambda(lt)
Age-Specific Survival Rate l_x
Description
The proportion of the original cohort that is still alive at age x,
obtained by summing the age-stage survival rates over all stages:
l_x = sum over j of s_xj.
Usage
calc_lx(lt, sxj = NULL)
Arguments
lt |
A |
sxj |
Optional; the result of |
Value
A data frame with the columns Age and l_x; a
terminal row with l_x = 0 is appended so that the survival
curve ends at zero.
References
Chi, H. (1988) Life-table analysis incorporating both sexes and variable development rates among individuals. Environmental Entomology 17(1), 26-34.
See Also
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
head(calc_lx(lt))
Age-Specific Fecundity m_x
Description
The age-specific fecundity of the cohort, computed from the female
age-stage survival rate, the age-specific female fecundity and the
overall survival rate: m_x = s_x,Female * F_xj / l_x. With this
definition sum(l_x * m_x) equals the net reproductive rate
calc_R0, so the Euler-Lotka equation solved by
calc_r is consistent.
Usage
calc_mx(lt, sxj = NULL, fxj = NULL, lx = NULL)
Arguments
lt |
A |
sxj |
Optional; the result of |
fxj |
Optional; the result of |
lx |
Optional; the result of |
Value
A data frame with the columns Age and m_x; a
terminal row with m_x = 0 is appended.
References
Chi, H. and Liu, H. (1985) Two new methods for the study of insect population ecology. Bull. Inst. Zool. Acad. Sin 24(2), 225-240.
See Also
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
head(calc_mx(lt))
Intrinsic Rate of Increase r
Description
The intrinsic rate of increase (instantaneous rate of natural
increase): the positive root of the Euler-Lotka equation
sum over x of l_x * m_x * exp(-r * x) = 1, where x runs over
the age classes (days) starting at 1. The root is located with the
bisection method on the interval [0, 1] (tolerance 1e-6, at most 100
iterations).
Usage
calc_r(lt, lx = NULL, mx = NULL)
Arguments
lt |
A |
lx |
Optional; the result of |
mx |
Optional; the result of |
Value
A single numeric value: the intrinsic rate of increase r (per day).
References
Birch, L. C. (1948) The intrinsic rate of natural increase of an insect population. Journal of Animal Ecology 17(1), 15-26.
See Also
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
calc_r(lt)
Age-Stage Survival Rate s_xj
Description
Calculates the age-stage survival rate: the proportion of the original
cohort that is alive and in developmental stage j at age x,
s_xj = n_xj / N, where n_xj is the number of individuals
of age x in stage j. This is the fundamental curve set of the
age-stage, two-sex life table: because individuals of the same age may
be in different stages, s_xj describes the cohort much better than a
single l_x curve.
Usage
calc_sxj(lt)
Arguments
lt |
A |
Details
The returned data frame has one row per age class (day) and
one column per stage, in the order of the stage names returned by
get_stage_names (immature stages first, then
"Female" and "Male").
Value
A data frame of age-stage survival rates (values in [0, 1]): rows = ages in days, columns = developmental stages.
References
Chi, H. and Liu, H. (1985) Two new methods for study of insect population ecology. Bull. Inst. Zool. Acad. Sin 24(2), 225-240.
Chi, H. (1988) Life-table analysis incorporating both sexes and variable development rates among individuals. Environmental Entomology 17(1), 26-34.
See Also
get_stage_names, calc_lx,
lifeTable_plot
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
head(calc_sxj(lt))
Check the Type of an Input Path
Description
Checks whether the input path points to a folder or to a file. Before the check, the path is cleaned automatically: backslashes are converted to forward slashes, invisible characters that are often copied along with paths from 'Windows' dialogs (U+202A) are removed, and a redundant trailing "/" is dropped.
Usage
check_path_type(path)
Arguments
path |
Character string; the path to check. Anything that is not a single, non-missing, non-empty character string is treated as invalid. |
Details
The function never stops: it always returns one of the four type labels below, so callers can branch directly on the result. The cleaned path is used for the existence checks, which makes the function robust against paths copied out of the 'Windows' Explorer address bar. It is used internally by the reading functions of the package to support both folder input (batch mode) and single-file input.
Value
A character string, one of
"folder" |
the path exists and is a folder |
"csv file" |
the path exists, is a file and has the extension csv |
"other file" |
the path exists and is a file with another extension |
"invalid path" |
the path does not exist or is not a valid path string |
See Also
Examples
check_path_type(tempdir())
check_path_type(system.file("extdata", "lc50_example.csv", package = "insectecol"))
Default Developmental Stage Names
Description
Generates the default stage names used throughout the package:
"Egg" followed by "1st instar", "2nd instar",
... one entry per immature stage. The adult labels
"Female"/"Male" are appended automatically by
get_stage_names and need not be included here.
Usage
default_stage_names(k)
Arguments
k |
Integer; number of immature stages (>= 1). |
Value
A character vector of length k.
Examples
default_stage_names(4) # "Egg", "1st instar", "2nd instar", "3rd instar"
Predict the Emergence Period from a Stage-Structure Survey
Description
Non-interactive, fully parameter-driven entry point for the
emergence-period module (the stage-grading method: one field
survey of the population stage structure — e.g. a
dissected-sample count of pupal grades — is turned into the
projected eclosion dates of the 16
the beginning, peak and end of the adult emergence period). In
the same style as gdd_analyze and
lc50_analyze, it (1) obtains the data — user
column vectors (stage = d$stage, count = d$n, days =
d$days), a whole data frame, or a csv/xlsx file / folder read
via emergence_read —, (2) computes the
cumulative development and the interpolated quantile dates via
emergence_calc and (3) optionally draws the
projection with plot.emergence. Larval hatch dates
are projected as well when pre_ovip / egg_days
are supplied. Nothing is written to disk unless plot_file
is supplied; tabular export is handled separately by
emergence_export.
Usage
emergence_analyze(
stage = NULL,
count = NULL,
percent = NULL,
days = NULL,
data = NULL,
path = NULL,
stage_col = NULL,
count_col = NULL,
percent_col = NULL,
days_col = NULL,
survey_date,
p = c(0.16, 0.5, 0.84),
labels = NULL,
pre_ovip = 0,
egg_days = 0,
encoding = "UTF-8",
header = TRUE,
pattern = "\\.(csv|xlsx|xls)$",
plot = FALSE,
plot_file = NULL,
show_hatch = TRUE,
plot_title = NULL,
plot_sub = NULL,
plot_xlab = NULL,
plot_ylab = NULL,
plot_family = NULL,
plot_width = 10.67,
plot_height = 6,
plot_units = c("in", "cm", "px"),
plot_res = 150,
...
)
Arguments
stage, count, days |
User-supplied column vectors, e.g.
|
percent |
Alternative to |
data |
A data.frame with a stage column, a count (or
percent) column and a days column. Used when the vectors are
not supplied; takes precedence over |
path |
Optional; path to a csv/xlsx file or a folder (batch
mode), read with |
stage_col, count_col, percent_col, days_col |
Column names; auto-detected by default (ignored when the column vectors are supplied). |
survey_date |
The survey date: a |
p |
Numeric vector of emergence quantiles, default
|
labels |
Optional labels of the quantiles, see
|
pre_ovip |
Pre-oviposition period in days (default 0 = not used). Counted from female eclosion to egg deposition. |
egg_days |
Egg duration in days (default 0 = not used). |
encoding, header, pattern |
Reading options for
|
plot |
Logical; whether to draw the projection (default
|
plot_file |
Optional png path: when supplied together with
|
show_hatch |
Plot option, see |
plot_title, plot_sub, plot_xlab, plot_ylab |
Plot options
(title, subtitle, axis labels); |
plot_family |
Text font family, see |
plot_width, plot_height, plot_units, plot_res |
Physical size
and resolution of the exported png (only used when
|
... |
Further arguments passed to |
Value
A list with components:
data |
the survey table actually analysed |
fit |
the |
plot_file |
the png path when |
See Also
emergence_read,
emergence_calc, emergence_export,
emergence_export_plot
Examples
f <- system.file("extdata", "emergence_example.csv",
package = "insectecol")
## --- way 1 (recommended): read the file yourself, pass columns in ---
d <- read.csv(f)
out <- emergence_analyze(stage = d$stage, count = d$count,
days = d$days, survey_date = "2026-03-20")
out$fit # three quantile dates
out$fit$table # cumulative development
predict(out$fit, c(0.25, 0.75)) # arbitrary quantiles
## --- way 2: pass the whole data frame ---
out2 <- emergence_analyze(data = d, survey_date = "2026-03-20")
## --- way 3: let the function read the file ---
out3 <- emergence_analyze(path = f, survey_date = "2026-03-20")
## --- hatch projection + png export + custom labels ---
## plot_title / plot_xlab / plot_ylab accept custom labels; Chinese
## labels are rendered through the device's font fallback (SimSun
## on Chinese Windows)
out4 <- emergence_analyze(path = f, survey_date = "2026-03-20",
pre_ovip = 3, egg_days = 10,
plot = TRUE,
plot_file = tempfile(fileext = ".png"))
out4$fit$predictions
Core Emergence-Period Calculation (Stage-Grading Method)
Description
Computes the emergence-period projection from one field survey of
the population stage structure (the classic Chinese
stage-grading method, fen ling fen ji tui suan fa). The
stages are ordered by their days to eclosion (most developed
first), the cumulative development share is built top-down and the
eclosion dates of the requested quantiles — by default 16
(beginning), 50
i.e. the mean +/- 1 SD of a normal emergence curve) — are
obtained by linear interpolation of the days-to-eclosion axis,
then anchored to the survey date. When pre_ovip /
egg_days are supplied, the larval hatch dates are projected
as well (eclosion + pre-oviposition period + egg duration).
Usage
emergence_calc(
data,
stage_col = NULL,
count_col = NULL,
percent_col = NULL,
days_col = NULL,
survey_date,
p = c(0.16, 0.5, 0.84),
labels = NULL,
pre_ovip = 0,
egg_days = 0
)
Arguments
data |
A data.frame with a stage column (character), a count or percent column (numeric) and a days column: the average days from that stage to adult eclosion at the current temperature. |
stage_col, count_col, percent_col, days_col |
Column names; auto-detected by default (English and Chinese aliases, e.g. stage / count / days or their Chinese equivalents). Exactly one of count / percent is required. |
survey_date |
The survey date: a |
p |
Numeric vector of emergence quantiles, default
|
labels |
Optional labels of the quantiles (same length as
|
pre_ovip |
Pre-oviposition period in days (default 0 = not used). |
egg_days |
Egg duration in days (default 0 = not used). |
Details
The quantiles that fall outside the surveyed cumulative range are linearly extrapolated from the outermost segment and flagged with a warning: a quantile below the share of the most developed stage has partially eclosed before the survey, a quantile above the share of the least developed stage indicates that younger stages were missed. Stages are sorted by days to eclosion, so the row order of the input is irrelevant; a stage sharing its days value with another stage is allowed but flagged (check the stage durations).
Value
A list of class "emergence":
survey_date |
the survey |
table |
data.frame: stage, count (or percent), proportion, cumulative share, days to eclosion, projected eclosion date |
predictions |
data.frame: label, p, interpolated days
(fractional, measured from the survey date), projected
calendar date, and |
interpolate |
closure |
n, n_stages, pre_ovip, egg_days, p, labels |
the inputs |
See Also
emergence_analyze (the main entry point),
emergence_read, emergence_export
Examples
## Overwintering-generation survey, 40 individuals (Tianyang case):
d <- data.frame(
stage = c("Pupal exuviae", paste("Pupa", 7:1), "Prepupa", "Larva 5"),
count = c(2, 3, 5, 7, 7, 5, 3, 4, 2, 2),
days = seq(0, 18, 2)) # days from that stage to eclosion
fit <- emergence_calc(d, survey_date = "2026-03-20")
fit # three quantile dates
fit$table # cumulative development
predict(fit, c(0.25, 0.75)) # arbitrary quantiles
## With the hatch projection (pre-oviposition 3 d + egg 10 d):
fit2 <- emergence_calc(d, survey_date = "2026-03-20",
pre_ovip = 3, egg_days = 10)
fit2$predictions
Save Emergence-Period Projection Results
Description
Saves the quantile predictions (eclosion dates, and hatch dates when present) as CSV (UTF-8) or xlsx. The cumulative-development table behind the projection is written alongside by default.
Usage
emergence_export(x, file = "emergence_results.csv", include_stages = TRUE, ...)
Arguments
x |
A |
file |
Output path; the format is chosen by the extension (.csv / .xlsx). |
include_stages |
Logical; whether to also write the cumulative-development table. Default TRUE. |
... |
Further arguments passed to |
Examples
f <- system.file("extdata", "emergence_example.csv",
package = "insectecol")
fit <- emergence_calc(emergence_read(f), survey_date = "2026-03-20")
emergence_export(fit, tempfile(fileext = ".csv"))
Export the Emergence-Period Plot as PNG
Description
Draws the emergence-period projection of an "emergence"
object on a png device ('ragg' when available, otherwise
png) and writes it to disk - the
standalone counterpart of plot_file = in
emergence_analyze, usable on an existing fit at any
time. All plot options of plot.emergence are
supported.
Usage
emergence_export_plot(
x,
file = "emergence_plot.png",
show_hatch = TRUE,
title = NULL,
sub = NULL,
xlab = NULL,
ylab = NULL,
family = NULL,
width = 10.67,
height = 6,
units = c("in", "cm", "px"),
res = 150,
...
)
Arguments
x |
A |
file |
Output png path. |
show_hatch, title, sub, xlab, ylab, family |
Plot options, see
|
width, height, units, res |
Physical size and resolution of the
png; the composition is identical at every resolution,
|
... |
Further arguments passed to
|
Value
Invisibly, file.
Examples
f <- system.file("extdata", "emergence_example.csv",
package = "insectecol")
fit <- emergence_calc(emergence_read(f), survey_date = "2026-03-20",
pre_ovip = 3, egg_days = 10)
emergence_export_plot(fit, tempfile(fileext = ".png"))
Read a Stage-Structure Survey from a File or a Folder
Description
Reads one field survey of the population stage structure for
emergence_calc: one row per stage, with a stage
name column, a count (or percent) column and a days-to-eclosion
column. The input may be a single csv file (delimiter
auto-detected), a single xlsx/xls file (via the 'readxl' package)
or a folder containing csv/xlsx files (batch mode; the files are
combined and the source file name kept in a source_file
column).
Usage
emergence_read(
path,
encoding = "UTF-8",
header = TRUE,
pattern = "\\.(csv|xlsx|xls)$"
)
Arguments
path |
Path to a csv/xlsx file or to a folder (batch mode). |
encoding |
Text encoding of csv files, default |
header |
Logical; whether the file(s) contain a header row. Default TRUE. |
pattern |
Regular expression selecting the files in batch mode; default: csv / xlsx / xls. |
Value
A data.frame (single file), or the combined data.frame with
an extra source_file column (folder input).
See Also
emergence_calc,
emergence_analyze
Examples
f <- system.file("extdata", "emergence_example.csv",
package = "insectecol")
d <- emergence_read(f)
head(d)
Analyse Temperature-Dependent Development (Main Function)
Description
Non-interactive, fully parameter-driven entry point for the
degree-day module, in the same style as
lifeTable_analyze and lc50_analyze. It
(1) obtains the long-format data — user-supplied column vectors
(temp = d$T, duration = d$days, group = d$stage), a whole
data frame, or a csv/xlsx file / folder read via
gdd_read —, (2) optionally validates the data with
gdd_check (including the linear-range check),
(3) fits the chosen model — or selects the best model per group
by AICc with model = "auto" — via gdd_calc
and (4) optionally draws the fitted curves with
gdd_plot — in the same style as the
lc50_analyze entry point of the bioassay module.
Nothing is written to disk unless plot_file is supplied;
tabular export is handled separately by gdd_export.
Usage
gdd_analyze(
temp = NULL,
duration = NULL,
group = NULL,
data = NULL,
path = NULL,
temp_col = NULL,
duration_col = NULL,
by = NULL,
model = c("linear", "logan", "lactin", "briere1", "briere2", "wang", "auto"),
start = NULL,
conf_level = 0.95,
min_n = 3,
maxiter = 1000,
check = TRUE,
encoding = "UTF-8",
header = TRUE,
temp_from_file = FALSE,
pattern = "\\.(csv|xlsx|xls)$",
plot = FALSE,
plot_file = NULL,
plot_group = NULL,
show_C = TRUE,
show_Topt = TRUE,
plot_title = NULL,
plot_sub = NULL,
plot_xlab = NULL,
plot_ylab = NULL,
plot_family = NULL,
plot_width = 10.67,
plot_height = 6,
plot_units = c("in", "cm", "px"),
plot_res = 150,
...
)
Arguments
temp, duration, group |
User-supplied column vectors, e.g.
|
data |
A data.frame in the long format required by
|
path |
Optional; path to a csv/xlsx file or a folder (batch
mode), read with |
temp_col, duration_col |
Column names; auto-detected by default (ignored when the column vectors are supplied). |
by |
Grouping variable(s), e.g. |
model |
Single model name or |
start |
Optional named list of starting values for a nonlinear
model, e.g. |
conf_level |
Confidence level, default 0.95. |
min_n |
Minimum rows per group, default 3. |
maxiter |
Iteration limit passed to the nonlinear fitter. |
check |
Logical; whether to validate the data with
|
encoding, header, temp_from_file, pattern |
Reading options for
|
plot |
Logical; whether to draw the fitted curves (default
|
plot_file |
Optional png path: when supplied together with
|
plot_group, show_C, show_Topt |
Plot options, see
|
plot_title |
Custom plot title; |
plot_sub |
Custom subtitle; |
plot_xlab, plot_ylab |
Custom axis labels; |
plot_family |
Text font family, see |
plot_width, plot_height |
Physical size of the exported figure
in |
plot_units |
Unit of |
plot_res |
Resolution (dpi) of the exported png, default 150.
Higher values add pixels (sharper print) without changing the
layout or the physical size. E.g. a journal requiring 300 dpi at
8 cm width: |
... |
Further arguments passed to |
Value
A list with components:
data |
the long-format data actually analysed |
check |
the |
fit |
the |
plot_file |
the png path when |
See Also
gdd_read, gdd_check,
gdd_calc, gdd_plot,
gdd_predict, gdd_compare,
gdd_export, gdd_export_plot,
gdd_daily
Examples
f <- system.file("extdata", "gdd_example.csv", package = "insectecol")
## --- way 1 (recommended): read the file yourself, pass columns in ---
## Typical when many data sets live in one csv: the user reads the
## file and picks the columns with $, exactly like lifeTable_analyze()
d <- read.csv(f)
out1 <- gdd_analyze(temp = d$temp, duration = d$duration, group = d$stage)
out1$fit$results # C, K, SE and CI per stage
summary(out1$fit) # detailed coefficient tables
## Without a grouping column: one overall model
out1b <- gdd_analyze(temp = d$temp, duration = d$duration)
## --- way 2: pass the whole data frame ---
out2 <- gdd_analyze(data = d, by = "stage")
gdd_predict(out2$fit, temp = c(20, 25), group = "Egg")
## --- way 3: let the function read the file ---
out3 <- gdd_analyze(path = f, by = "stage")
## --- AICc model selection + png export + custom labels ---
## plot_title / plot_xlab / plot_ylab accept custom labels; Chinese
## labels are rendered through the device's font fallback
out4 <- gdd_analyze(temp = d$temp, duration = d$duration, group = d$stage,
model = "auto", plot = TRUE,
plot_file = tempfile(fileext = ".png"))
out4$fit$comparison # full comparison table, best flag included
Compute Effective Accumulated Temperature and Developmental Parameters (Linear or Nonlinear Models)
Description
Fits a temperature-dependent development model to constant- temperature data. By default the classic linear degree-day model
V = (T - C) / K
is fitted by ordinary least
squares, yielding the developmental threshold temperature C
(deg C) and the effective accumulated temperature K
(degree-days). Nonlinear models describing the full response curve
(optimum and upper threshold included) are available via
model.
Usage
gdd_calc(
data,
temp_col = NULL,
duration_col = NULL,
by = NULL,
model = c("linear", "logan", "lactin", "briere1", "briere2", "wang", "auto"),
start = NULL,
conf_level = 0.95,
min_n = 3,
maxiter = 1000
)
Arguments
data |
A data.frame with at least a temperature column and a duration column. |
temp_col, duration_col |
Column names (auto-detected by default). |
by |
Grouping variable(s), e.g. |
model |
Single model name or |
start |
Optional named list of starting values for a nonlinear
model, e.g. |
conf_level |
Confidence level, default 0.95. |
min_n |
Minimum rows per group, default 3. |
maxiter |
Iteration limit passed to |
Details
Available models:
-
"linear"(default):V = (T - C)/K. Analytic OLS; the only model providingK. -
"logan": Logan-6 (Logan et al. 1976). Does NOT define a lower threshold; givesT_mandT_{opt}. -
"lactin": Lactin et al. (1995).\lambda < 0lets the curve cross zero, so the lower threshold is derived numerically. -
"briere1":V = aT(T - T_0)\sqrt{T_m - T}(Briere et al. 1999);T_0is the lower threshold. -
"briere2":V = aT(T - T_0)(T_m - T)^{1/m};madds flexibility. -
"wang": Wang et al. (1982), 7 parameters — needs at least 9 temperature points. -
"auto": fits all candidates and selects the best per group by AICc; the full comparison table is stored inobject$comparison.
Nonlinear fits use nls (port algorithm,
bounded) with heuristic starting values and deterministic restarts
(start entries not belonging to the fitted model are
ignored). Standard errors are asymptotic; derived quantities
(Topt, Vmax, numerically derived C) carry no
SE. Each nonlinear model requires at least (number of parameters +
2) temperature points.
Value
A "gdd" object: results (summary table, one row
per group; the selected model in "auto" mode), fits
(per-group details), data (cleaned data), and
comparison (model comparison table, "auto" only).
See Also
[gdd_read()], [gdd_check()], [gdd_compare()], [gdd_predict()], [gdd_plot()], [gdd_export()], [gdd_daily()]
Examples
# csv example shipped with the package (inst/extdata)
f <- system.file("extdata", "gdd_example.csv", package = "insectecol")
df <- gdd_read(f)
fit1 <- gdd_calc(df, by = "stage") # linear (default)
fit2 <- gdd_calc(df, by = "stage", model = "briere1") # nonlinear
fit3 <- gdd_calc(df, by = "stage", model = "auto") # AICc selection
Check Developmental Data (Long Format) Before Fitting
Description
Non-stopping validation of a long-format development data frame (one
row per observation with temperature and duration columns), i.e. the
layout required by gdd_calc. Reports per-row problems
(missing / non-numeric / non-positive values), a per-group summary
(sample sizes, temperature coverage) and a linear-range check: if
the highest mean developmental rate is not reached at the highest
temperature, the data contain a high-temperature decline and the
linear model must not be fitted to the full range.
Usage
gdd_check(data, temp_col = NULL, duration_col = NULL, by = NULL)
Arguments
data |
A data.frame with temperature and duration columns. |
temp_col, duration_col |
Column names (auto-detected by default). |
by |
Optional grouping variable(s), as in |
Value
A list:
valid |
logical vector, one entry per row of |
problems |
data.frame (row, column, reason); empty if none |
group_summary |
data.frame per group: n, n_temp, temperature and duration ranges |
linear_check |
data.frame per group: temperature of the
maximal mean rate, highest temperature, |
data |
the valid rows, standardised to columns temp / duration / rate / group (NULL if no valid row remains) |
See Also
Examples
f <- system.file("extdata", "gdd_example.csv", package = "insectecol")
chk <- gdd_check(gdd_read(f), by = "stage")
chk$group_summary # per-group sample sizes and ranges
chk$linear_check # is the maximal mean rate at the highest temperature?
Compare Temperature-Development Models
Description
Fits all candidate models (linear + nonlinear) per group and returns a comparison table with R-squared, RMSE, AIC, AICc, BIC, delta-AICc and the best model (smallest AICc). Useful for reporting model selection tables in publications.
Usage
gdd_compare(
data,
temp_col = NULL,
duration_col = NULL,
by = NULL,
models = c("linear", "logan", "lactin", "briere1", "briere2", "wang"),
start = NULL,
conf_level = 0.95,
min_n = 3,
maxiter = 1000
)
Arguments
data, temp_col, duration_col, by |
Same as in [gdd_calc()]. |
models |
Character vector of candidate models; default is all
six. |
start, conf_level, min_n, maxiter |
Same as in [gdd_calc()]. |
Value
A data.frame with columns: group, model,
n, converged, k, R2, RMSE,
AIC, AICc, BIC, note,
delta_AICc, best.
Examples
f <- system.file("extdata", "gdd_example.csv", package = "insectecol")
gdd_compare(gdd_read(f), by = "stage")
Daily Accumulation of Degree-Days (Field Application)
Description
Accumulates daily degree-days above the developmental threshold temperature, useful for predicting field phenology (e.g. the date on which a stage completes its effective accumulated temperature K).
Usage
gdd_daily(Tmin, Tmax, C, method = c("avg", "triangle"))
Arguments
Tmin, Tmax |
Numeric vectors of daily minimum / maximum temperatures (deg C). |
C |
Developmental threshold temperature (deg C), e.g. taken
from a |
method |
|
Value
A list with daily, cumulative and total.
Examples
gdd_daily(c(8, 10, 12), c(20, 22, 25), C = 11)$total
Save Degree-Day Analysis Results
Description
Saves the analysis results as CSV (UTF-8) or xlsx. The summary
table (results, one row per group) is always written; the
model-comparison table (available when model = "auto" was
used), per-group coefficient tables with confidence intervals, and
the cleaned data can be included optionally.
Usage
gdd_export(
x,
file = "gdd_results.csv",
include_data = FALSE,
include_coefs = FALSE,
include_comparison = TRUE,
...
)
Arguments
x |
A |
file |
Output path; the format is chosen by the extension (.csv / .xlsx). |
include_data |
Logical; whether to also write the cleaned data. Default FALSE. |
include_coefs |
Logical; whether to write the per-group coefficient tables (estimate, SE, t, p, CI). Default FALSE. |
include_comparison |
Logical; whether to write the model
comparison table when it exists (only |
... |
Further arguments passed to |
Examples
f <- system.file("extdata", "gdd_example.csv", package = "insectecol")
fit <- gdd_calc(gdd_read(f), by = "stage")
gdd_export(fit, tempfile(fileext = ".csv"))
Export the Degree-Day Plot as PNG
Description
Draws the degree-day figure of a "gdd" object on a png
device ('ragg' when available, otherwise png)
and writes it to disk - the standalone counterpart of
plot_file = in gdd_analyze, usable on an
existing fit at any time. All plot options of gdd_plot
are supported.
Usage
gdd_export_plot(
x,
file = "gdd_plot.png",
group = NULL,
show_C = TRUE,
show_Topt = TRUE,
title = NULL,
sub = NULL,
xlab = NULL,
ylab = NULL,
family = NULL,
width = 10.67,
height = 6,
units = c("in", "cm", "px"),
res = 150,
...
)
Arguments
x |
A |
file |
Output png path. |
group, show_C, show_Topt, title, sub, xlab, ylab, family |
Plot
options, see |
width, height, units, res |
Physical size and resolution of the
png; the composition is identical at every resolution,
|
... |
Further arguments passed to |
Value
Invisibly, file.
Examples
f <- system.file("extdata", "gdd_example.csv", package = "insectecol")
fit <- gdd_calc(gdd_read(f), by = "stage")
gdd_export_plot(fit, tempfile(fileext = ".png"),
title = "Developmental rate vs temperature")
Plot Developmental Rate vs Temperature with the Fitted Model
Description
Draws a scatter plot of the developmental rate against temperature with the fitted model. For the linear model the threshold temperature C is marked where the fitted line crosses V = 0; for nonlinear models the fitted curve is drawn and C / Topt / the upper threshold are marked where defined.
Usage
gdd_plot(
x,
group = NULL,
show_C = TRUE,
show_Topt = TRUE,
title = NULL,
sub = NULL,
family = "serif",
xlab = "Temperature T (deg C)",
ylab = "Developmental rate V (1/d)",
...
)
Arguments
x |
A |
group |
Character vector of group names to plot; default is all groups. |
show_C |
Logical; whether to mark the threshold temperature C. Default TRUE. |
show_Topt |
Logical; whether to mark the optimum temperature (nonlinear models only). Default TRUE. |
title |
Plot title. |
sub |
Plot subtitle (bottom line). |
family |
Text font family used for the title, axis labels and
tick labels. Default |
xlab, ylab |
Axis labels. |
... |
Further graphical parameters passed to |
Examples
f <- system.file("extdata", "gdd_example.csv", package = "insectecol")
fit <- gdd_calc(gdd_read(f), by = "stage")
gdd_plot(fit, group = "Egg")
## Custom title, subtitle and axis labels (portable English example):
gdd_plot(fit, group = "Egg",
title = "Developmental rate vs temperature",
sub = "Constant-temperature rearing experiment, 2026")
## Chinese titles are rendered through the device's font fallback
## (SimSun on Chinese 'Windows'); note that the plain pdf() device
## cannot embed CJK glyphs on many platforms, so draw on a png or
## cairo device for Chinese titles.
Predict Developmental Duration at Given Temperatures
Description
Evaluates the fitted model (linear or nonlinear) at the given
temperatures and returns the predicted developmental rate and
duration D = 1 / V.
Usage
gdd_predict(object, temp, group = NULL)
Arguments
object |
A |
temp |
Numeric vector of target temperatures (deg C). |
group |
Character vector of group names to predict; default is all groups. |
Value
A data.frame with columns: group, temp,
pred_rate, pred_duration, within_range.
Examples
f <- system.file("extdata", "gdd_example.csv", package = "insectecol")
fit <- gdd_calc(gdd_read(f), by = "stage")
gdd_predict(fit, temp = c(20, 24, 28), group = "Egg")
Read Insect Developmental Data from a Folder or a File
Description
Reads constant-temperature development data in long format (one row per observation, with a temperature column and a duration column; optional grouping columns such as life stage). The input may be:
a single csv file (delimiter auto-detected),
a single xlsx/xls file (via the 'readxl' package),
a folder containing csv/xlsx files (batch mode), e.g. one file per temperature or per stage; the files are combined and the source file name is kept in a
source_filecolumn.
Usage
gdd_read(
path,
encoding = "UTF-8",
header = TRUE,
temp_from_file = FALSE,
pattern = "\\.(csv|xlsx|xls)$"
)
Arguments
path |
Path to a csv/xlsx file or to a folder (batch mode). |
encoding |
Text encoding of csv files, default |
header |
Logical; whether the file(s) contain a header row. Default TRUE. |
temp_from_file |
Logical (batch mode only); if TRUE, the file
name (extension stripped) is converted to a number and written to
the |
pattern |
Regular expression selecting the files in batch mode; default: csv / xlsx / xls. |
Value
A data.frame (single file), or the combined data.frame with
an extra source_file column (folder input).
See Also
check_path_type (path handling),
gdd_check, gdd_calc
Examples
# Single csv file shipped with the package (inst/extdata)
f <- system.file("extdata", "gdd_example.csv", package = "insectecol")
df <- gdd_read(f)
head(df)
# Batch mode: one csv per temperature, temperature from the file names
d <- system.file("extdata", "gdd_batch", package = "insectecol")
df2 <- gdd_read(d, temp_from_file = TRUE)
head(df2)
Extract the Developmental Stage Names from the Header
Description
Extracts the names of the developmental stages from the header (first
row) of a life table csv file. The header is truncated at the sex
column, the ID column is dropped, and the two adult labels before the
sex column are replaced by "Female" and "Male".
Usage
get_stage_names(lt)
Arguments
lt |
A |
Details
Stage names are taken from the header exactly as they are
spelled in the csv file, so English headers produce English stage
names and Chinese headers produce Chinese stage names. Only the two
adult labels are always converted to "Female" and
"Male". Internally the sex column is located by matching the
header entry gender and the ID column by the header entry
ID (both are fixed parts of the csv template).
Value
A character vector of stage names, e.g.
c("Egg", "Larva", "Pupa", "Female", "Male"); used as column
names by calc_sxj and as legend labels by
lifeTable_plot.
See Also
lifeTable_read, calc_sxj,
lifeTable_plot
Examples
lt <- lifeTable_read(system.file("extdata", "lifetable_example.csv",
package = "insectecol"))
get_stage_names(lt)
Analyse Bioassay Data for LC Estimation (Main Function)
Description
Non-interactive, fully parameter-driven entry point for the LC
(lethal concentration) analysis. It (1) assembles the standardised
data list from a data frame, a named list of data frames or three
parallel vectors, (2) computes the LC estimates with the selected
method(s) via lc50_calculate and (3) optionally builds
the regression plot(s) in the style of lc50_plot,
optionally written to disk as png when plot_file is supplied.
Tabular export is handled separately by lc50_export.
Usage
lc50_analyze(
d = NULL,
concentration = NULL,
tested = NULL,
dead = NULL,
name = "bioassay",
lc = 0.5,
method = "traditional",
plot = FALSE,
plot_file = NULL,
plot_width = 12,
plot_height = 8,
plot_units = "cm",
plot_res = 300,
plot_method = NULL,
font = "TNM",
unit = NULL,
shape = c("sigmoid", "linear"),
ci = TRUE,
ci_level = 0.95,
error_bar = TRUE,
move_thres = 0.5,
lc_ci = TRUE,
lc_p = TRUE,
lc_lab_gap = 0.35,
lc_lab_gap_right = 0.1,
lc_lab_dy = 0.1,
lc_lab_lh = 1.05
)
Arguments
d |
Optional; the bioassay data: a data frame with the columns
|
concentration, tested, dead |
Numeric vectors; the concentration,
the number of insects tested and the number of dead insects, one
entry per concentration group (replicates = repeated values).
Used only when |
name |
Character; the data set name used in the results and the
saved plot file names when |
lc |
Numeric; the lethal proportion (default 0.5 = LC50,
e.g. 0.9 = LC90), passed to |
method |
Character; one or several of |
plot |
Logical; whether to build the regression plot(s)
(default |
plot_file |
Optional png path: when supplied together with
|
plot_width, plot_height, plot_units, plot_res |
Physical size and
resolution of the exported png (only used when |
plot_method |
Character; which of the computed methods to plot
(default |
font, unit, shape, ci, ci_level, error_bar, move_thres, lc_ci, lc_p, lc_lab_gap, lc_lab_gap_right, lc_lab_dy, lc_lab_lh |
Plot settings, passed to the internal plot engine exactly as in
|
Value
A list with elements data (the standardised data
list, one data frame per data set), results (the list
returned by lc50_calculate: results,
summary_df, lc), plot (a named list of
ggplot objects when plot = TRUE, otherwise NULL)
and plot_file (the written path(s) when plot_file
was supplied, otherwise NULL).
See Also
lc50_read, lc50_calculate,
lc50_plot, lc50_export,
lc50_export_plot
Examples
## way 1: data frame straight from the package example csv
f <- system.file("extdata", "lc50_example.csv", package = "insectecol")
out1 <- lc50_analyze(lc50_read(f), method = "probit")
out1$results$summary_df
## way 2: three parallel vectors, no csv involved; all three methods
conc <- c(0, 1.5, 3, 6, 12, 24)
n <- c(120, 60, 60, 60, 60, 60)
dead <- c(7, 9, 18, 32, 48, 57)
out2 <- lc50_analyze(concentration = conc, tested = n, dead = dead,
name = "trial1", method = "all")
out2$results$summary_df
## way 3: LC90, improved regression, plot on the linear axis
out3 <- lc50_analyze(concentration = conc, tested = n, dead = dead,
name = "trial1", lc = 0.9, method = "improved",
plot = TRUE, plot_method = "improved",
shape = "linear")
out3$plot$trial1 # ggplot object: print(), customise or export
Batch Calculation of LC Values
Description
Computes the LC estimates for every data set read by
lc50_read, using the selected estimation method(s), and
returns both the detailed per-file results and a summary data frame.
Usage
lc50_calculate(lcd, lc = 0.5, method = "traditional")
Arguments
lcd |
The named list returned by |
lc |
Numeric; the lethal proportion for which the concentration is estimated. The default 0.5 gives the LC50, 0.9 the LC90. |
method |
Character string or vector; the estimation method(s) to
use: one or several of |
Details
The selected method(s) are applied to every data set; the
default is the traditional linear regression. The summary data
frame gets one row per file and method, and the progress log
reports the status of every method for every file. A file that
fails (e.g. because too few valid concentrations remain after the
Abbott correction) does not interrupt the batch: the error
message is recorded in the Equation column of the summary
data frame instead.
Value
A list with elements
results |
nested list: one element per file, each holding one element per selected method with its result list (or the error message) |
summary_df |
data frame with one row per file and method: estimate, 95 goodness-of-fit |
lc |
the lethal proportion used |
References
Finney, D. J. (1971) Probit Analysis, 3rd edition. Cambridge University Press, Cambridge.
See Also
lc50_read, lc50_traditional,
lc50_improved, lc50_probit,
lc50_plot, lc50_export
Examples
f <- system.file("extdata", "lc50_example.csv", package = "insectecol")
res <- lc50_calculate(lc50_read(f), lc = 0.7) # LC70
res$summary_df
lc50_calculate(lc50_read(f), method = "all")$summary_df # all methods
Export LC Results to 'Excel'
Description
Writes the results of lc50_calculate into a multi-sheet
'Excel' workbook: a summary sheet with the LC estimates, confidence
intervals and regression parameters of all files and methods, plus
one detail sheet per file with the preprocessed data and the
parameters of the successfully computed methods.
Usage
lc50_export(results, output_dir = NULL, filename = "LC50_results.xlsx")
Arguments
results |
The result list returned by
|
output_dir |
Character string; the output folder. If |
filename |
Character string; the name of the output file
(default |
Details
The detail sheet of each file contains the preprocessed data (concentration, tested and dead insects, raw and corrected mortality, log concentration and probit) followed by a parameter block of every method that succeeded for that file. Files for which no method succeeded get an empty sheet.
Value
The full path of the exported xlsx file (invisibly).
See Also
Examples
f <- system.file("extdata", "lc50_example.csv", package = "insectecol")
lc50_export(lc50_calculate(lc50_read(f)), output_dir = tempdir())
Save the LC Results of Every Data File (One xlsx per csv)
Description
Reads the csv file(s) at path, computes the LC values with
lc50_calculate and writes one 'Excel' workbook per csv
file with lc50_export - named after the data file and
placed next to the raw data.
Usage
lc50_export_auto(path = NULL, lc = 0.5, method = "traditional", suffix = NULL)
Arguments
path |
Character string; a csv file or a folder with csv files,
classified with |
lc |
Numeric; the lethal proportion, passed on to
|
method |
Character string; the estimation method, passed on to
|
suffix |
Optional character string appended to the output file
names, e.g. |
Details
Each csv file is processed completely on its own (read,
calculate, export) in its own loop pass, so the outputs of
different files can never mix. LB_48.csv produces
LB_48.xlsx in the same folder; for a folder every csv file
inside is processed the same way. A file that cannot be read is
skipped with a message (a single-file input that cannot be read is
an error); a file whose computation fails still gets its workbook
with the error recorded in the summary sheet. Non-default
settings are appended to the names so repeated runs do not
overwrite each other: lc = 0.9 gives
LB_48_LC90.xlsx, method = "probit" gives
LB_48_probit.xlsx.
Value
The paths of the written xlsx files, invisibly.
See Also
lc50_export_plot_auto for the matching figure
export, lc50_export for a custom output location
Examples
f <- system.file("extdata", "lc50_example.csv", package = "insectecol")
tmp <- file.path(tempdir(), "lc50_example.csv")
file.copy(f, tmp, overwrite = TRUE)
lc50_export_auto(tmp) # -> <tempdir>/bioassay.xlsx
Save LC50 Plots
Description
Saves one plot or a list of plots from lc50_plot, like
ggsave(path, plot, device = "tiff", width = 12, height = 8,
dpi = 300, units = "cm", bg = "white") but with the dpi handling of
lc50_plot applied. The same plot object can be written at any
dpi without being re-created.
Usage
lc50_export_plot(
plot,
path = NULL,
device = "tiff",
width = 12,
height = 8,
dpi = 300,
units = "cm",
bg = "white",
...
)
Arguments
plot |
A ggplot or a (named) list of ggplots. |
path |
Output file (single plot) or folder (list of plots, or a
path without extension); |
device, width, height, units, bg |
Passed on to |
dpi |
Resolution of the written file (default 300). |
... |
Further arguments passed on to |
Value
Path(s) of the written file(s), invisibly.
See Also
Examples
f <- system.file("extdata", "lc50_example.csv", package = "insectecol")
plots <- lc50_plot(lc50_calculate(lc50_read(f)))
lc50_export_plot(plots$bioassay, file.path(tempdir(), "LC50_demo.tiff"))
Save the LC Figure of Every Data File (One image per csv)
Description
Reads the csv file(s) at path, computes the LC values, draws
the regression plot of lc50_plot for every file and
saves it with lc50_export_plot - named after the data
file and placed next to the raw data.
Usage
lc50_export_plot_auto(
path = NULL,
lc = 0.5,
method = "traditional",
suffix = NULL,
device = "tiff",
dpi = 600,
width = 12,
height = 8,
units = "cm",
bg = "white",
font = "TNM",
unit = NULL,
shape = c("sigmoid", "linear"),
ci = TRUE,
ci_level = 0.95,
error_bar = TRUE,
move_thres = 0.5,
lc_ci = TRUE,
lc_p = TRUE,
lc_lab_gap = 0.35,
lc_lab_gap_right = 0.1,
lc_lab_dy = 0.1,
lc_lab_lh = 1.05,
preview = FALSE
)
Arguments
path, lc, method, suffix |
Same as |
device, width, height, dpi, units, bg |
Figure settings, passed on
to |
font, unit, shape, ci, ci_level, error_bar, move_thres, lc_ci, lc_p, lc_lab_gap, lc_lab_gap_right, lc_lab_dy, lc_lab_lh |
Plot settings, passed on to |
preview |
Logical (default |
Details
The pipeline and the file-naming rules are the same as in
lc50_export_auto, plus _linear for
shape = "linear": LB_48.csv gives LB_48.tiff,
lc = 0.9, method = "probit" gives
LB_48_LC90_probit.tiff. The two functions are fully
independent: each reads and computes the data on its own, so they
can be called alone or in any order. A file whose computation
fails gets no figure. With method = "all" the figure shows
the first method that succeeded.
Value
Invisibly a list with elements plots (named list of
the ggplot objects, e.g. for print() or
lc50_export_plot(plots, ...)) and files (paths of the
written images).
See Also
lc50_export_auto, lc50_plot,
lc50_export_plot
Examples
f <- system.file("extdata", "lc50_example.csv", package = "insectecol")
tmp <- file.path(tempdir(), "lc50_example.csv")
file.copy(f, tmp, overwrite = TRUE)
lc50_export_plot_auto(tmp) # -> <tempdir>/bioassay.tiff
LC Estimation by the Improved Linear Regression Method
Description
Estimates the lethal concentration with a weighted least-squares line: the same probit-log transformation as the traditional method, but each concentration is weighted by the inverse of the variance of its observed mortality, which makes the regression more robust.
Usage
lc50_improved(d, lc = 0.5)
Arguments
d |
Same as |
lc |
Same as |
Details
The weights are the inverse-variance (optimal) weights of
the probit transform, w = n * phi(z)^2 / (p * (1 - p)),
where n is the number of insects tested, p the
corrected mortality and z = qnorm(p) the corresponding
standard normal quantile: the variance of a probit-transformed
mortality is p * (1 - p) / (n * phi(z)^2), smallest at
intermediate mortalities and growing without bound at the
extremes. Therefore concentrations with mortalities near 50
large sample sizes dominate the fit, while near-0
near-100
delta-method confidence interval and the goodness-of-fit test are
computed exactly as in lc50_traditional.
Value
Same as lc50_traditional.
References
Finney, D. J. (1971) Probit Analysis, 3rd edition. Cambridge University Press, Cambridge.
See Also
LC50 Regression Plots
Description
Plots every data set: observed points, the fitted curve of the computed
method with its pointwise confidence band, and dashed reference lines
marking the LC estimate, which is itself marked by a circle where it
lies on the fitted curve. By default the concentration axis is on a
log10 scale, which gives the classical symmetric S-shaped curve;
shape = "linear" restores the original linear axis.
Usage
lc50_plot(
results,
save_path = NULL,
font = "TNM",
width = 7,
height = 6,
dpi = 300,
unit = NULL,
shape = c("sigmoid", "linear"),
ci = TRUE,
ci_level = 0.95,
error_bar = TRUE,
move_thres = 0.5,
method = NULL,
lc_ci = TRUE,
lc_p = TRUE,
lc_lab_gap = 0.35,
lc_lab_gap_right = 0.1,
lc_lab_dy = 0.1,
lc_lab_lh = 1.05
)
Arguments
results |
Result list of |
save_path |
Folder for the png files; |
font |
Font family (default |
width, height |
Figure size in inches (default 7 x 6). |
dpi |
Resolution of the saved files (default 300); at any dpi the figures keep the physical size they have at 300 dpi. |
unit |
Unit of the concentration (e.g. |
shape |
|
ci |
Logical (default |
ci_level |
Confidence level of the curve band and of the replicate error bars (default 0.95). |
error_bar |
Logical (default |
move_thres |
Numeric (default 0.5). A dashed reference line that
does not land on a regular tick normally gets an extra tick whose
value is labelled next to the axis like a regular tick. If the LC
position is at most |
method |
Character scalar, which methods to plot: a subset of
|
lc_ci |
Logical (default |
lc_p |
Logical (default |
lc_lab_gap |
Clearance between the vertical reference line and the near edge of the LC label when the label sits LEFT of the line, in text widths of the label itself (default 0.35). Larger pushes the label further away from the line; smaller moves it towards it. |
lc_lab_gap_right |
The same clearance when the label sits RIGHT
of the line (default 0.1, smaller than |
lc_lab_dy |
Clearance between the LC label block and the LC
crossing, in y-axis units (default 0.1): the distance from the
crossing to the edge of the block that faces it. The block is
placed in the diagonal quadrant the fitted curve never enters
(above the crossing when the label sits left of the vertical
reference line, below it when the label sits right), anchored by
that facing edge, so adding lines or changing |
lc_lab_lh |
Line spacing of the LC label in multiples of its
font size (1 = single spacing, default 1.05). The lines are spaced
evenly whichever of them |
Details
Replicates of the same concentration are pooled and drawn as
the Abbott-corrected pooled mortality with Wilson score intervals.
The LC reference label is centred around the crossing of the two
dashed reference lines. Because the sigmoid only ever passes
through the lower-left and upper-right quadrants around that
crossing, the label is placed in one of the two free ones: above
the crossing when it sits left of the vertical reference line,
below it when it sits right, at a clearance of lc_lab_dy.
If a replicate error bar reaches into the label block, the block is
shifted vertically by the smallest amount that restores a clearance
of about one line height from the bar end, preferring the direction
that keeps it on its own side of the crossing. The extra x-axis
value always sits to the right of the vertical dashed line (it
moves to the left only when it would run off the right panel
edge); when the label block dips into the value's strip, the block
is raised clear of it instead.
Value
Named list of ggplot objects (invisibly).
File names
Saved files are named after the data set plus suffixes for every
non-default setting that changes the look (_linear for
shape = "linear", _noband for ci = FALSE,
_nobar for error_bar = FALSE, _nolcCI for
lc_ci = FALSE, _nochi for lc_p = FALSE, and the
selected method names), so plots saved to one folder can never
overwrite each other.
See Also
Examples
f <- system.file("extdata", "lc50_example.csv", package = "insectecol")
res <- lc50_calculate(lc50_read(f))
plots <- lc50_plot(res, save_path = tempdir())
plots <- lc50_plot(res, shape = "linear", save_path = tempdir()) # original axis
plots <- lc50_plot(res, ci = FALSE, error_bar = FALSE,
save_path = tempdir()) # bare version
LC Estimation by Probit Analysis (Maximum Likelihood)
Description
Estimates the lethal concentration by maximum-likelihood probit analysis in the sense of Finney: a binomial generalized linear model with probit link fitted by iteratively reweighted least squares.
Usage
lc50_probit(d, lc = 0.5)
Arguments
d |
Same as |
lc |
Same as |
Details
Unlike the two regression methods, the line is fitted by
maximum likelihood (a quasibinomial GLM with probit link, fitted by
iteratively reweighted least squares) to the Abbott-corrected
proportions p = (p_raw - p_c) / (1 - p_c) with the numbers
tested as weights (the classic Finney effective-counts
formulation), rather than by least squares to probit-transformed
points. Groups with a corrected mortality of exactly 0
are dropped, as in the two regression methods. A quasibinomial
family is used, so the covariance matrix of the coefficients
incorporates the heterogeneity factor (Pearson chi-square divided
by the residual degrees of freedom): the confidence intervals are
automatically widened when the data show more variation than the
binomial assumption allows. The reported chi-square statistic and
its p value serve as a goodness-of-fit test of the probit-log
concentration line.
Value
Same as lc50_traditional (with fit being
the fitted glm object).
References
Finney, D. J. (1971) Probit Analysis, 3rd edition. Cambridge University Press, Cambridge.
See Also
lc50_traditional, lc50_improved
Read Bioassay Data for LC Estimation
Description
Reads the raw csv files of a dose-response bioassay (one file per insecticide, population or similar) and returns a list of standardised data frames that the LC functions of the package work with.
Usage
lc50_read(path = NULL)
Arguments
path |
Character string; the data path: a folder (all csv files
inside are read) or a single csv file. If |
Details
Each csv file must contain one row per concentration with three required columns: the concentration, the number of insects tested and the number of dead insects. The column names are matched loosely against the fixed keywords of the csv template, so headers with additional text such as units (e.g. a concentration header with "(mg/L)" appended) are recognised as well. Rows with a concentration of zero are treated as the control group and are used for the Abbott correction during the analysis.
The data are standardised and validated while reading: rows with non-numeric or missing entries are dropped, the number of tested insects must be positive, the number of dead insects must lie between zero and the number of tested insects, at least one concentration greater than zero must be present, and the rows are sorted by increasing concentration. The file encoding is detected automatically (UTF-8 with BOM and GBK are tried), so files written by both English and Chinese versions of 'Excel' can be read.
Value
A named list with one data frame per csv file; the list
elements are named after the files (without extension) and each
data frame has the columns Concentration, Tested and
Dead.
References
Abbott, W. S. (1925) A method of computing the effectiveness of an insecticide. Journal of Economic Entomology 18(2), 265-267.
See Also
lc50_calculate for the analysis workflow,
check_path_type for the path handling.
Examples
f <- system.file("extdata", "lc50_example.csv", package = "insectecol")
lcd <- lc50_read(f)
lcd$bioassay
if (interactive()) lcd <- lc50_read() # interactive folder dialog
LC Estimation by the Traditional Linear Regression Method
Description
Estimates the lethal concentration by fitting an ordinary (unweighted) least-squares line to the probit-transformed mortality.
Usage
lc50_traditional(d, lc = 0.5)
Arguments
d |
A data frame with the columns |
lc |
Numeric; the lethal proportion for which the concentration is estimated. The default 0.5 gives the LC50, 0.9 the LC90. |
Details
The corrected mortalities are transformed to probits
(y = qnorm(p) + 5) and the concentrations to common
logarithms (x = log10(concentration)); the line
y = a + b * x is fitted by ordinary least squares with all
points weighted equally. Inverting the line at the probit that
corresponds to the requested lethal proportion gives
LC = 10^((y0 - a) / b) with y0 = qnorm(lc) + 5. The
95
covariance matrix of the regression coefficients on the log scale
and back-transformed to the concentration scale. A Pearson
chi-square goodness-of-fit test of the observed against the fitted
mortalities is attached.
Mortalities are corrected for natural mortality in the control group with the Abbott (1925) formula, and concentrations with a corrected mortality of exactly 0 undefined) are dropped before fitting; at least 3 valid concentrations are required.
Value
A list with elements
method |
name of the estimation method |
lc |
the lethal proportion used |
estimate |
the LC estimate |
lower, upper |
limits of the 95% confidence interval |
intercept, slope |
the regression coefficients a and b |
se_slope |
standard error of the slope |
equation |
the regression equation as a character string |
r2 |
coefficient of determination |
chisq, chi_df, p_chi |
Pearson chi-square statistic, degrees of freedom and p value of the goodness-of-fit test |
n_groups |
number of concentration groups used in the fit |
dropped |
number of concentration groups dropped |
fit |
the fitted model object |
prep |
the preprocessed data |
References
Finney, D. J. (1971) Probit Analysis, 3rd edition. Cambridge University Press, Cambridge.
Abbott, W. S. (1925) A method of computing the effectiveness of an insecticide. Journal of Economic Entomology 18(2), 265-267.
See Also
lc50_improved for the weighted version,
lc50_probit for the maximum-likelihood version,
lc50_calculate for the batch workflow.
Analyse a Life Table from User-Supplied Columns (Main Function)
Description
Non-interactive, fully parameter-driven entry point for the
age-stage, two-sex life table analysis. It (1) builds a
life_table object from column vectors of an already loaded
data frame (e.g. after data <- read.csv("XXX.csv"), or accepts
a ready life_table object), (2) computes the life table
parameters and (3) optionally draws the age-stage survival curves
with customisable title, axis titles and legend labels, optionally
written to disk as png when plot_file is supplied. Tabular
export is handled separately by lifeTable_export.
Usage
lifeTable_analyze(
lt = NULL,
stages = NULL,
adult_days = NULL,
sex = NULL,
oviposition = NULL,
stage_names = NULL,
file_name = "life_table",
check = TRUE,
fecundity = TRUE,
bootstrap = FALSE,
B = 1e+05,
seed = NULL,
plot = FALSE,
title = NULL,
x_title = "Age(days)",
y_title = "Age-Stage Survival Rate(Sxj)",
legend_labels = NULL,
dpi = 300,
plot_file = NULL,
plot_width = 12,
plot_height = 8,
plot_units = "cm",
plot_res = 300
)
Arguments
lt |
Optional; an existing |
stages, adult_days, sex, oviposition, stage_names, file_name, check |
Passed to |
fecundity |
Logical; whether to compute the reproduction-related
parameters (F, F_xj, m_x, R0, r, lambda, T). |
bootstrap |
Logical; whether to estimate the standard errors and
percentile confidence intervals of all scalar parameters with the
bootstrap technique of TWOSEX-MSChart via
|
B |
Integer; number of bootstrap replicates (only used when
|
seed |
Integer; seed of the bootstrap random number generator
(only used when |
plot |
Logical; whether to draw the age-stage survival curves
(default |
title |
Character; plot title. |
x_title, y_title |
Character; axis titles. Defaults
|
legend_labels |
Character vector; legend labels, one per stage
(immature stages + Female + Male), e.g.
|
dpi |
Numeric; resolution used for scaling the text of the plot (default 300). |
plot_file |
Optional png path: when supplied together with
|
plot_width, plot_height, plot_units, plot_res |
Physical size and
resolution of the exported png (only used when |
Value
A list with components lt (the life_table
object), results (the list returned by
lifeTable_calculate_all; additionally containing
boot, the lifeTable_bootstrap result, when
bootstrap = TRUE), plot (the ggplot object when
plot = TRUE, otherwise NULL) and plot_file
(the png path when plot_file was supplied, otherwise
NULL).
See Also
lifeTable_build,
lifeTable_calculate_all, lifeTable_bootstrap,
lifeTable_plot, lifeTable_export
Examples
## The example raw data shipped with the package (the same layout as
## the csv template: ID + immature stage columns + Adult + gender +
## one column per oviposition day of the females)
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
## ^^ change "lifeTable" to the actual package name
d <- read.csv(f)
names(d) # with check.names = TRUE (default) the names become
# ID, Egg, X1st.instar, X2nd.instar, ..., Prepupa, Pupa,
# Adult, gender, ...
## --- way 1: pass a column-range subset of the data frame
## (positional indexing: works regardless of how the names were mangled)
out1 <- lifeTable_analyze(stages = d[2:8], adult_days = d$Adult,
sex = d$gender, oviposition = d[, 11:17],
file_name = "Example - way 1")
out1$results$N # number of individuals
out1$results$R0 # net reproductive rate
## --- with bootstrap standard errors (small B for a fast example;
## use the default B = 100000 for publications)
out1b <- lifeTable_analyze(stages = d[2:8], adult_days = d$Adult,
sex = d$gender, oviposition = d[, 11:17],
file_name = "Example - way 1",
bootstrap = TRUE, B = 2000, seed = 1)
out1b$results$boot$summary
## --- way 2: pass a named list of single columns
## (the list names become the stage names in plots and results)
out2 <- lifeTable_analyze(stages = list(Egg = d[[2]], "1st instar" = d[[3]],
"2nd instar" = d[[4]], "3rd instar" = d[[5]],
"4th instar" = d[[6]], Prepupa = d[[7]],
Pupa = d[[8]]),
adult_days = d$Adult, sex = d$gender,
fecundity = FALSE) # survival analysis only,
# oviposition not supplied
out2$results$N
## --- way 3: select the stage columns by their original names
## (re-read with check.names = FALSE to keep "1st instar", "2nd instar", ...)
d3 <- read.csv(f, check.names = FALSE)
out3 <- lifeTable_analyze(stages = d3[, c("Egg", "1st instar", "2nd instar",
"3rd instar", "4th instar",
"Prepupa", "Pupa")],
adult_days = d3$Adult, sex = d3$gender,
oviposition = d3[, 11:17],
stage_names = c("Egg", "L1", "L2", "L3", "L4",
"Prepupa", "Pupa"),
plot = TRUE,
legend_labels = c("Egg", "L1", "L2", "L3", "L4",
"Prepupa", "Pupa",
"Female", "Male"))
out3$plot # print or further customise the ggplot object
Paired Bootstrap Test Between Two Life Tables
Description
Compares the life table parameters of two cohorts with the paired
bootstrap test used by TWOSEX-MSChart: both cohorts are resampled
independently B times, the differences
d = parameter(group 1) - parameter(group 2) are formed
replicate by replicate, and the 95 percent percentile interval of
the differences is inspected. Following the convention of the
life table literature, the difference is considered significant
when the confidence interval of the difference does not include
zero.
Usage
lifeTable_boot_test(lt1, lt2, B = 1e+05, seed = NULL, conf.level = 0.95)
Arguments
lt1, lt2 |
|
B |
Integer; number of bootstrap replicates per group
(default |
seed |
Integer; seed for the random number generator; the session state is restored when the function exits. |
conf.level |
Numeric; confidence level of the intervals of
the differences (default |
Details
The two cohorts are resampled independently, so they do
not need to have the same number of individuals. The parameters
compared are those of lifeTable_bootstrap that
occur in BOTH cohorts; if the stage structures differ, only the
common parameters are compared and a warning is issued. A
bootstrap p-value is reported in addition to the interval test:
2 * min(P(d <= 0), P(d >= 0)) over the valid replicates.
Replicates in which a parameter is undefined in either group
(e.g. no female drawn) are dropped from the comparison.
Value
A data frame with one row per compared parameter:
Parameter |
parameter name (as in
|
Boot_mean_1, Boot_mean_2 |
bootstrap means of the two groups |
Diff |
mean of the bootstrap differences (group 1 minus group 2) |
CI_low, CI_high |
percentile interval of the differences |
Significant |
logical; |
P_bootstrap |
two-sided bootstrap p-value |
The attribute groups contains the file names of the two
cohorts.
References
Meyer, J. S., Ingersoll, C. G., McDonald, L. L. and Boyce, M. S. (1986) Estimating uncertainty in population growth rates: jackknife vs. bootstrap. Ecological Modelling 29, 251-271.
Chi, H., You, M. S., Atlihan, R., Smith, C. L., Kavousi, A., Ozgokce, M. S., Guncan, A. and Tuan, S. J. (2020) Age-stage, two-sex life table: an introduction to theory, data analysis, and application. Entomologia Generalis 40(2), 103-124.
See Also
lifeTable_bootstrap for the standard errors
of a single cohort.
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt1 <- lifeTable_read(f)
## compare the full cohort with its first half (demo only - a real
## comparison would use two different treatments)
lt2 <- lt1
lt2$data <- lt1$data[1:12, ]
rownames(lt2$data) <- NULL
lt2$file_name <- "Example (first half)"
## B = 100000 is the recommended setting for publications; a smaller
## B is used here so that the example runs fast
lifeTable_boot_test(lt1, lt2, B = 2000, seed = 1)
Bootstrap Standard Errors of Life Table Parameters
Description
Estimates the standard errors and percentile confidence intervals
of all scalar life table parameters with the bootstrap technique
used by TWOSEX-MSChart: complete individual records (stage
durations, adult days, sex and daily oviposition) are resampled
with replacement B times, and every parameter is recomputed
from each resampled cohort. Individuals that died before the adult
stage are resampled as well - they carry their mortality and zero
fecundity into the replicates.
Usage
lifeTable_bootstrap(lt, B = 1e+05, seed = NULL, conf.level = 0.95)
Arguments
lt |
A |
B |
Integer; number of bootstrap replicates. The published
TWOSEX-MSChart standard is |
seed |
Integer; seed for the random number generator. Set it
to make the results exactly reproducible; |
conf.level |
Numeric; confidence level of the percentile
intervals (default |
Details
The parameters covered are the mean developmental time of
every immature stage (averaged over the individuals that entered
the stage, including those that died during it), the female and
male adult longevity, and - when oviposition data are present -
the mean fecundity F, the net reproductive rate R0, the intrinsic
rate of increase r, the finite rate of increase lambda and the
mean generation time T. The intrinsic rate is solved per
replicate from the Euler-Lotka equation with the same age
convention as calc_r, but with a widened search
interval so that declining cohorts (R0 < 1, i.e. r < 0) are also
handled. Replicates in which no female is drawn have NA
fecundity, and replicates without any offspring have NA
r, lambda and T; such replicates are
excluded from the means, standard errors and intervals of the
affected parameters (column Valid_B shows how many
remained). Curve-type outputs (s_xj, l_x, m_x, e_x) are not
bootstrapped.
Attach the result to an analysis to have it exported by
lifeTable_export:
results$boot <- lifeTable_bootstrap(lt).
Value
An object of class life_table_boot: a list with
summary |
data frame; one row per parameter with the original point estimate, the bootstrap mean, the bootstrap standard error and the percentile confidence interval |
boot |
numeric matrix; the raw B x p replicate values |
B, conf.level, N, parameters |
the settings used |
References
Meyer, J. S., Ingersoll, C. G., McDonald, L. L. and Boyce, M. S. (1986) Estimating uncertainty in population growth rates: jackknife vs. bootstrap. Ecological Modelling 29, 251-271.
Efron, B. and Tibshirani, R. J. (1993) An Introduction to the Bootstrap. New York: Chapman and Hall.
Chi, H., You, M. S., Atlihan, R., Smith, C. L., Kavousi, A., Ozgokce, M. S., Guncan, A. and Tuan, S. J. (2020) Age-stage, two-sex life table: an introduction to theory, data analysis, and application. Entomologia Generalis 40(2), 103-124.
See Also
lifeTable_boot_test for the paired
bootstrap test between two cohorts,
lifeTable_calculate_all for the point estimates.
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
## B = 100000 is the recommended setting for publications; a smaller
## B is used here so that the example runs fast
bt <- lifeTable_bootstrap(lt, B = 2000, seed = 1)
bt$summary
Build a Life Table Object from User-Supplied Columns
Description
Assembles a life_table object (the same structure returned by
lifeTable_read) from individual column vectors already
loaded into the R session, e.g. after
data <- read.csv("XXX.csv"). This is the entry point for
analysing data that do not come from a package-conform csv file.
Usage
lifeTable_build(
stages,
adult_days,
sex,
oviposition = NULL,
stage_names = NULL,
file_name = "life_table",
check = TRUE
)
Arguments
stages |
Stage-duration columns, one column per immature stage: a data frame, a matrix or a list of equal-length vectors (column j = days spent in immature stage j; blank/NA for stages not reached). If it is a named data frame/list, the names are used as stage names. |
adult_days |
Numeric vector; adult survival days (NA for individuals that died before the adult stage). |
sex |
Character/factor vector; |
oviposition |
Optional; daily oviposition records, one column per
day: a data frame, a matrix (rows = individuals in the same order as
|
stage_names |
Character vector of stage names (length =
number of columns of |
file_name |
Character; data set name (default plot title, base name of the exported xlsx). |
check |
Logical; validate the data with
|
Value
A life_table object, ready for all calc_*,
lifeTable_plot and lifeTable_export functions.
Examples
## The raw example data shipped with the package
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
## ^^ change to the actual package name
d <- read.csv(f)
## 1) Standard build: column-range subset of stage columns + adult days
## + sex + oviposition columns (positional indexing is robust to
## the space-containing headers like "1st instar")
lt1 <- lifeTable_build(d[2:8], adult_days = d$Adult, sex = d$gender,
oviposition = d[, 11:17], file_name = "Example")
names(lt1) # components of the life_table object
head(lt1$df) # wide table: ID + stages + Adult + gender + oviposition
## 2) Survival analysis only: omit oviposition entirely. Legal since
## the data checker skips the oviposition check when the table ends
## at the sex column (use fecundity = FALSE in the analysis).
lt2 <- lifeTable_build(d[2:8], adult_days = d$Adult, sex = d$gender)
## 3) Named list: the list names become the stage names
lt3 <- lifeTable_build(list(Egg = d[[2]], "1st instar" = d[[3]],
"2nd instar" = d[[4]], "3rd instar" = d[[5]],
"4th instar" = d[[6]], Prepupa = d[[7]],
Pupa = d[[8]]),
adult_days = d$Adult, sex = d$gender,
oviposition = d[, 11:17])
## 4) Friendly stage names via stage_names: exactly one per IMMATURE
## stage. The adult labels "Female" and "Male" are appended
## automatically and must NOT be included.
lt4 <- lifeTable_build(d[2:8], adult_days = d$Adult, sex = d$gender,
oviposition = d[, 11:17],
stage_names = c("Egg", "L1", "L2", "L3", "L4",
"Prepupa", "Pupa"))
## 5) A common mistake, handled gracefully: stage_names wrongly
## including the adult labels. The extra two entries are dropped
## with a warning (only a WARNING - the build still succeeds).
lt5 <- lifeTable_build(d[2:8], adult_days = d$Adult, sex = d$gender,
oviposition = d[, 11:17],
stage_names = c("Egg", "L1", "L2", "L3", "L4",
"Prepupa", "Pupa",
"Female", "Male"))
## 6) Skip the consistency check (e.g. oviposition columns
## deliberately shorter than the adult life span)
lt6 <- lifeTable_build(d[2:8], adult_days = d$Adult, sex = d$gender,
oviposition = d[, 11:17], check = FALSE)
Batch Analysis of Life Table Data
Description
Runs the complete workflow (reading, validation, calculation, plotting
and exporting) for every csv file in a folder, or for a single csv
file. Each data set gets its own 'Excel' workbook; in addition an
all.xlsx with the summary of all files is created. Files that
fail (e.g. because of data errors) are skipped and reported at the end
without interrupting the remaining files.
Usage
lifeTable_calculate(
path,
output_path = NULL,
plot = TRUE,
keep_tiff = FALSE,
dpi = 300,
bootstrap = FALSE,
B = 1e+05,
seed = NULL
)
Arguments
path |
Character; the data path: a folder (all csv files inside
are analysed) or a single csv file. The type of the path is
determined by |
output_path |
Character; the export folder. Defaults to the parent folder of the csv file (single-file mode) or the data folder itself (folder mode). |
plot |
Logical; whether the age-stage survival curves are
generated and embedded into the workbooks (default |
keep_tiff |
Logical; whether to keep the standalone tiff files
(default |
dpi |
Numeric; resolution of the exported images (default 300). |
bootstrap |
Logical; whether to estimate the standard errors
and percentile confidence intervals of all scalar parameters of
every file with |
B |
Integer; number of bootstrap replicates per file (only
used when |
seed |
Integer; base seed of the bootstrap random number
generator (only used when |
Value
A summary data frame with one row per successfully analysed
file (population parameters as columns, plus their bootstrap
standard errors as _SE columns when bootstrap =
TRUE); the attribute error_files contains the names of
the files that failed.
See Also
lifeTable_read, lifeTable_calculate_all,
lifeTable_bootstrap, lifeTable_plot,
lifeTable_export
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lifeTable_calculate(f, output_path = file.path(tempdir(), "insectecol-demo"))
Calculate All Parameters of One Life Table
Description
Convenience wrapper that computes all life table parameters of one data set in a single call: cohort size, mean fecundity, the age-stage survival rates, the age-specific rates and the derived population parameters (R0, r, lambda, T).
Usage
lifeTable_calculate_all(lt, fecundity = TRUE)
Arguments
lt |
A |
fecundity |
Logical; whether to compute the reproduction-related
parameters (F, F_xj, m_x, R0, r, lambda, T). |
Details
The intermediate results are passed on internally, so nothing
is computed twice: s_xj first, then l_x, F_xj and m_x, then r and
R0, and finally lambda = exp(r) and T = log(R0) / r.
Value
A named list with elements N, F, sxj,
lx, fxj, mx, ex, R0, r,
lambda and T
With fecundity = FALSE (or when no oviposition data are
supplied), fxj and mx are NULL and F,
R0, r, lambda, T are NA_real_.
See Also
The individual calc_* functions;
lifeTable_calculate for the batch workflow.
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
results <- lifeTable_calculate_all(lt)
results$R0
lifeTable_calculate_all(lt, fecundity = FALSE)$N
Validate a Life Table Data Set
Description
Checks the age data (illegal characters, negative values, illegal gaps) and verifies for every female that the number of her oviposition records matches her recorded survival days. If a problem is found, the function stops and reports the exact row and column positions of all offending cells.
Usage
lifeTable_check(lt)
Arguments
lt |
A |
Details
Two kinds of problems are detected:
-
age data errors: cells in the stage-duration and survival-day columns that contain illegal characters or negative values, or illegal gaps within a sequence of values;
-
oviposition errors: for every female row, the number of non-empty daily fecundity cells must equal the adult survival days recorded in column
n - 1.
The check runs automatically inside lifeTable_read
unless check = FALSE is used there.
Value
invisible(TRUE) if no error is found; otherwise the
function stops with a detailed error message.
See Also
Save the Results of One Life Table Analysis
Description
Writes all results of one data set into a multi-sheet 'Excel' workbook
(<file name>_out.xlsx): the population parameters, the
age-stage survival rates, the age-specific rates and, optionally, the
survival curve plot.
Usage
lifeTable_export(
lt,
results,
output_path = getwd(),
plot = NULL,
keep_tiff = FALSE,
dpi = 300
)
Arguments
lt |
A |
results |
The result list returned by
|
output_path |
Character; folder the workbook is written to. Defaults to the current working directory. |
plot |
A ggplot object (usually from |
keep_tiff |
Logical; whether to keep the standalone tiff file
next to the workbook in addition to the copy embedded in it. Default
|
dpi |
Numeric; resolution of the exported image (default 300). |
Details
The tiff is written through the internal lt_ggsave(),
which enables 'showtext' for the export device and pins the 'showtext'
internal dpi to the value the text sizes of lifeTable_plot
are calibrated for. The exported figure therefore looks the same in
every R session, no matter what 'showtext' settings are left over in
the session. If the reproduction-related parameters were skipped
(fecundity = FALSE in lifeTable_calculate_all),
the corresponding values in the Summary sheet are NA and the
sheets "Female fecundity (F_xj)" and "Age-specific fecundity (m_x)"
are omitted. If bootstrap results are attached
(results$boot <- lifeTable_bootstrap(lt); done automatically
by lifeTable_analyze and
lifeTable_calculate when bootstrap = TRUE), an
extra worksheet "Bootstrap (SE & CI)" with the parameter table
(original estimate, bootstrap mean, standard error, percentile
confidence interval) is written.
Value
The path of the exported xlsx file (invisibly).
See Also
lifeTable_calculate, lifeTable_plot
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
results <- lifeTable_calculate_all(lt)
lifeTable_export(lt, results, tempdir())
Age-Stage Survival Rate Curves
Description
Draws the age-stage survival rate s(x,j) of every developmental stage (including the female and male adults) against age in days, in the style of the classical TWOSEX-MSChart plots.
Usage
lifeTable_plot(
lt,
sxj = NULL,
title = NULL,
x_title = "Age(days)",
y_title = "Age-Stage Survival Rate(Sxj)",
legend_labels = NULL,
dpi = 300
)
Arguments
lt |
A |
sxj |
Optional; the result of |
title |
Character; plot title. Defaults to the name of the csv file. |
x_title |
Character; x axis title (default |
y_title |
Character; y axis title (default
|
legend_labels |
Character vector; legend labels, one per stage
(immature stages plus |
dpi |
Numeric; resolution (default 300). Only influences the scaling of the graphical elements (title, axis labels, legend), so that the plot looks identical at 300 and 600 dpi. |
Details
To keep the figure clean, each stage is drawn only over the age window in which it actually occurs (extended by two days on both sides). Immature stages are drawn as coloured dots connected by a thin line; females are grey and males black, both with diamond points. By default all text of the figure is in English; title, axis titles and legend labels can be customised.
The text sizes are calibrated for being drawn while 'showtext' is
active at its default internal dpi (96); lifeTable_export
takes care of this when exporting. If you save the plot yourself,
switch 'showtext' on around the ggsave call,
otherwise the text comes out about 300/96 times too large.
Value
A ggplot object that can be customised further or saved with
ggsave.
See Also
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
p <- lifeTable_plot(lifeTable_read(f))
Read an Age-Stage, Two-Sex Life Table from a csv File
Description
Reads a raw csv file containing the individual daily records of an
age-stage, two-sex life table experiment and
returns a life_table object, the central data structure that all
other functions of the package work with.
Usage
lifeTable_read(path, check = TRUE)
Arguments
path |
Character string; path to the csv file. |
check |
Logical; if |
Details
The csv file contains one row per individual. If the sex
column is located at column n, the layout must be:
column 1: individual ID (header
ID),columns 2 to
n - 2: number of days spent in each developmental stage (egg, larva, ..., pupa),column
n - 1: adult survival days,column
n: sex, codedF(female),M(male) orN(died before the adult stage),columns
n + 1onward: daily oviposition of the females (one column per day; cells after the death of a female stay empty).
The first line of the file must contain the stage names as column
headers, including the ID column (ID) and the sex column
(gender). The sex column is located automatically by scanning the
first data row for the markers F/M/N. The file
encoding is detected automatically, so UTF-8 and GBK files are both
supported.
Value
A life_table object; a named list with components
data |
data frame with the raw csv content |
file_name |
file name without extension |
n |
column index of the sex column |
n_1 |
|
n_2 |
|
header |
the first row of the file (stage names), as character |
encoding |
the detected file encoding |
path |
the full path of the csv file |
References
Chi, H. and Liu, H. (1985) Two new methods for study of insect population ecology. Bull. Inst. Zool. Acad. Sin 24(2), 225-240.
Chi, H. (1988) Life-table analysis incorporating both sexes and variable development rates among individuals. Environmental Entomology 17(1), 26-34.
See Also
lifeTable_check for data validation,
lifeTable_calculate for the complete analysis workflow.
Examples
f <- system.file("extdata", "lifetable_example.csv", package = "insectecol")
lt <- lifeTable_read(f)
head(lt$data[, 1:5])
Plot an Emergence-Period Projection
Description
Draws the cumulative development curve of the survey (stage shares accumulated from the most developed stage downwards) against the projected eclosion dates, marks the quantile crossings (16 projection exists, arrows from each eclosion date to the corresponding hatch date. The quantile dates are listed in a legend box on the right-hand side of the figure (one row per quantile, with a true arrow glyph instead of the character combination "->").
Usage
## S3 method for class 'emergence'
plot(
x,
show_hatch = TRUE,
title = NULL,
sub = NULL,
family = "serif",
cex = 2,
lwd = 2,
legend_right = TRUE,
xlab = "Projected eclosion date",
ylab = "Cumulative development (%)",
...
)
Arguments
x |
A |
show_hatch |
Logical (default TRUE); whether to draw the hatch arrows when a hatch projection exists. |
title |
Plot title; |
sub |
Plot footnote; |
family |
Text font family. Default |
cex |
Overall text-size multiplier. Default |
lwd |
Overall line-width multiplier. Default |
legend_right |
Logical (default TRUE); whether the quantile
legend is placed outside the panel on the right-hand side
( |
xlab, ylab |
Axis labels. |
... |
Further graphical parameters passed to |
Examples
f <- system.file("extdata", "emergence_example.csv",
package = "insectecol")
fit <- emergence_calc(emergence_read(f), survey_date = "2026-03-20",
pre_ovip = 3, egg_days = 10)
plot(fit)
## the projection is fully customisable (title, axis labels, font
## family); Chinese labels are rendered through the device's font
## fallback (SimSun on Chinese 'Windows'):
plot(fit, title = "Stage-grading projection",
xlab = "Projected eclosion date",
ylab = "Cumulative development (%)")
Quantiles of an Emergence-Period Projection
Description
Returns the projected eclosion (or hatch) dates of arbitrary emergence quantiles.
Usage
## S3 method for class 'emergence'
predict(object, p, event = c("eclosion", "hatch"), ...)
Arguments
object |
A |
p |
Optional numeric vector of quantiles (0-1). The default
(missing |
event |
|
... |
Further arguments (unused). |
Value
A data.frame with columns p, days
(fractional days after the survey date) and date.
Examples
d <- data.frame(stage = c("Pupa 2", "Pupa 1", "Prepupa"),
count = c(3, 4, 3), days = c(12, 14, 16))
fit <- emergence_calc(d, survey_date = "2026-03-20",
pre_ovip = 3, egg_days = 10)
predict(fit) # the stored 16/50/84 predictions
predict(fit, c(0.25, 0.75)) # arbitrary eclosion quantiles
predict(fit, c(0.25, 0.75), event = "hatch")
Print an Emergence-Period Projection
Description
Prints the projected eclosion dates (and hatch dates, when requested) of the emergence quantiles.
Usage
## S3 method for class 'emergence'
print(x, ...)
Arguments
x |
A |
... |
Further arguments (unused). |
Summarise an Emergence-Period Projection
Description
Prints the full cumulative-development table behind the projection and the quantile predictions.
Usage
## S3 method for class 'emergence'
summary(object, ...)
Arguments
object |
A |
... |
Further arguments (unused). |
Value
Invisibly, a list with table (the cumulative
development) and predictions (the quantile dates).