| Type: | Package |
| Title: | Insect Ecology Data Analysis Toolkit |
| Version: | 1.0.1 |
| Description: | A collection of analytical tools for insect ecology research, currently covering age-stage, two-sex life table analysis and dose-response bioassays. The life table module 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, with Abbott correction, 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'. Planned extensions include more insect ecology indicators, such as median lethal temperature/time (LT50) and thermal constants (effective accumulated temperature). |
| 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: | testthat (≥ 3.0.0) |
| 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-09-16 05:58:02 UTC; SeaGhost |
| Author: | Wangyao Li [aut, cre, cph] |
| Maintainer: | Wangyao Li <1561941342@qq.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-09-27 16:10:07 UTC |
Build a Life Table Object from User-Supplied Columns
Description
Assembles a life_table object (the same structure returned by
read_life_table) 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
build_life_table(
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_*,
plot_sxj and save_results functions.
Examples
## The raw example data shipped with the package
f <- system.file("extdata", "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 <- build_life_table(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 <- build_life_table(d[2:8], adult_days = d$Adult, sex = d$gender)
## 3) Named list: the list names become the stage names
lt3 <- build_life_table(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 <- build_life_table(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 <- build_life_table(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 <- build_life_table(d[2:8], adult_days = d$Adult, sex = d$gender,
oviposition = d[, 11:17], check = FALSE)
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", "Example.csv", package = "insectecol")
lt <- read_life_table(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", "Example.csv", package = "insectecol")
lt <- read_life_table(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", "Example.csv", package = "insectecol")
lt <- read_life_table(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", "Example.csv", package = "insectecol")
lt <- read_life_table(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", "Example.csv", package = "insectecol")
lt <- read_life_table(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", "Example.csv", package = "insectecol")
lt <- read_life_table(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", "Example.csv", package = "insectecol")
lt <- read_life_table(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", "Example.csv", package = "insectecol")
lt <- read_life_table(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", "Example.csv", package = "insectecol")
lt <- read_life_table(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", "Example.csv", package = "insectecol")
lt <- read_life_table(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,
plot_sxj
Examples
f <- system.file("extdata", "Example.csv", package = "insectecol")
lt <- read_life_table(f)
head(calc_sxj(lt))
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
check_life_table(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 read_life_table
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
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", "bioassay.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"
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
plot_sxj.
See Also
read_life_table, calc_sxj,
plot_sxj
Examples
lt <- read_life_table(system.file("extdata", "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 plot_lc50.
Nothing is written to disk and no dialog is opened; export is
handled separately by save_lc50 /
save_lc50_plot.
Usage
lc50_analyze(
d = NULL,
concentration = NULL,
tested = NULL,
dead = NULL,
name = "bioassay",
lc = 0.5,
method = "traditional",
plot = FALSE,
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_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) and plot (a named list of
ggplot objects when plot = TRUE, otherwise NULL).
See Also
read_lc50, lc50_calculate,
plot_lc50, save_lc50
Examples
## way 1: data frame straight from the package example csv
f <- system.file("extdata", "bioassay.csv", package = "insectecol")
out1 <- lc50_analyze(read_lc50(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
read_lc50, 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
read_lc50, lc50_traditional,
lc50_improved, lc50_probit,
plot_lc50, save_lc50
Examples
f <- system.file("extdata", "bioassay.csv", package = "insectecol")
res <- lc50_calculate(read_lc50(f), lc = 0.7) # LC70
res$summary_df
lc50_calculate(read_lc50(f), method = "all")$summary_df # all methods
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
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
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. Nothing is
written to disk; export is handled separately by
save_results.
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,
plot = FALSE,
title = NULL,
x_title = "Age(days)",
y_title = "Age-Stage Survival Rate(Sxj)",
legend_labels = NULL,
dpi = 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). |
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). |
Value
A list with components lt (the life_table
object), results (the list returned by
lifeTable_calculate_all) and plot (the ggplot
object when plot = TRUE, otherwise NULL).
See Also
build_life_table,
lifeTable_calculate_all, plot_sxj,
save_results
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", "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$Summary # all life table parameters
## --- 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
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
)
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). |
Value
A summary data frame with one row per successfully analysed
file (population parameters as columns); the attribute
error_files contains the names of the files that failed.
See Also
read_life_table, lifeTable_calculate_all,
plot_sxj, save_results
Examples
f <- system.file("extdata", "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", "Example.csv", package = "insectecol")
lt <- read_life_table(f)
results <- lifeTable_calculate_all(lt)
results$R0
lifeTable_calculate_all(lt, fecundity = FALSE)$N
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
plot_lc50(
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.
Value
Named list of ggplot objects (invisibly).
See Also
Examples
f <- system.file("extdata", "bioassay.csv", package = "insectecol")
res <- lc50_calculate(read_lc50(f))
plots <- plot_lc50(res, save_path = tempdir())
plots <- plot_lc50(res, shape = "linear", save_path = tempdir()) # original axis
plots <- plot_lc50(res, ci = FALSE, error_bar = FALSE,
save_path = tempdir()) # bare version
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
plot_sxj(
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); save_results
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", "Example.csv", package = "insectecol")
p <- plot_sxj(read_life_table(f))
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
read_lc50(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", "bioassay.csv", package = "insectecol")
lcd <- read_lc50(f)
lcd$bioassay
if (interactive()) lcd <- read_lc50() # interactive folder dialog
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
read_life_table(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
check_life_table for data validation,
lifeTable_calculate for the complete analysis workflow.
Examples
f <- system.file("extdata", "Example.csv", package = "insectecol")
lt <- read_life_table(f)
head(lt$data[, 1:5])
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
save_lc50(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", "bioassay.csv", package = "insectecol")
save_lc50(lc50_calculate(read_lc50(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 save_lc50 - named after the data file and
placed next to the raw data.
Usage
save_lc50_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
save_lc50_plot_auto for the matching figure
export, save_lc50 for a custom output location
Examples
f <- system.file("extdata", "bioassay.csv", package = "insectecol")
tmp <- file.path(tempdir(), "bioassay.csv")
file.copy(f, tmp, overwrite = TRUE)
save_lc50_auto(tmp) # -> <tempdir>/bioassay.xlsx
Save LC50 Plots
Description
Saves one plot or a list of plots from plot_lc50, like
ggsave(path, plot, device = "tiff", width = 12, height = 8,
dpi = 300, units = "cm", bg = "white") but with the dpi handling of
plot_lc50 applied. The same plot object can be written at any
dpi without being re-created.
Usage
save_lc50_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", "bioassay.csv", package = "insectecol")
plots <- plot_lc50(lc50_calculate(read_lc50(f)))
save_lc50_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 plot_lc50 for every file and
saves it with save_lc50_plot - named after the data
file and placed next to the raw data.
Usage
save_lc50_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
save_lc50_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
save_lc50_plot(plots, ...)) and files (paths of the
written images).
See Also
save_lc50_auto, plot_lc50,
save_lc50_plot
Examples
f <- system.file("extdata", "bioassay.csv", package = "insectecol")
tmp <- file.path(tempdir(), "bioassay.csv")
file.copy(f, tmp, overwrite = TRUE)
save_lc50_plot_auto(tmp) # -> <tempdir>/bioassay.tiff
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
save_results(
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 showtext's
internal dpi to the value the text sizes of plot_sxj
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.
Value
The path of the exported xlsx file (invisibly).
See Also
Examples
f <- system.file("extdata", "Example.csv", package = "insectecol")
lt <- read_life_table(f)
results <- lifeTable_calculate_all(lt)
save_results(lt, results, tempdir())