Amount by Group function

Introduction

amountByGroup() is a utility function designed to summarise data from a single data table by one or more grouping variables, and it requires the user to specify the variables of interest to produce the outputs.

It is particularly suited for workflows where: * Tables are previously prepared (e.g. joins, recoding, lookups done before) * Both numeric and categorical variables need to be summarised * The same summarisation logic should be reused across different tables

The function works on one table at a time and produces either summary tables or simple bar plots.

It supports:

  • Numeric variables -> summarised by sum(), with optional percentage conversion (asPct = TRUE).
  • Categorical variables -> summarised as frequency counts.
  • Multiple variables can be summarised at once:
  • Numeric variables -> aggregated together in wide format.
  • Categorical variables -> produce frequency tables by group.
  • Filters can be applied prior to summarisation using a named list.
  • Results can be optionally assigned to the global environment using assign_to_global = TRUE.
  • Output options:
  • "table": returns a data.table (or list of tables if mixed types). (Output type used by default)
  • "plot": generates one or more ggplot2 visualisations.
  • Safe use inside packages

Note: The function intentionally does not perform joins or lookups — all preparation (e.g. species code → species name) should be done before calling it.

library(RDBEScore)
library(RDBESvisualise)

Example data

For illustration, small examples of reproducible datasets, similar to RDBES data, are created.


library(data.table)
#> 
#> Attaching package: 'data.table'
#> The following object is masked from 'package:base':
#> 
#>     %notin%


CL <- data.table(
  Year = c('2021', '2021', '2021', '2021', '2022', '2022', '2021', '2021'),
  Quarter = c(1, 1, 2, 1, 2, 2, 1, 2),
  Country = c('ZW','ZW','ST','ST','ST','YM','YM','YM'),
  Species = c("COD", "HKE", "COD", "COD", "HKE", "HKE", "COD", "HKE"),
  WeightKg = c(100, 50, 200, 120, 80, 30, 10, 100),
  ValueEUR = c(300, 150, 600, 360, 240, 100, 50, 150)
  )

CE <- data.table(
  Year = c('2021', '2021', '2021', '2021', '2022', '2022', '2021', '2021'),
  Quarter = c(1, 1, 2, 1, 2, 2, 1, 2),
  Country = c('ZW','ZW','ST','ST','ST','YM','YM','YM'),
  Area = c('34.7','34.5','34.7','34.5','34.5','34.7','34.7','34.5'),
  NumDomTrip = c(3500, 300, 2010, 500, 250, 2600, 5000, 1000)
)

SA <- data.table(
  Year = c('2021', '2021', '2021', '2022', '2022'),
  Quarter = c(1, 1, 2, 1, 2),
  Species = c("COD", "HKE", "COD", "COD", "HKE"),
  CatchCategory = c("Lan", "Lan", "Dis", "Lan", "Dis"),
  totalWtMes = c(100, 50, 20, 120, 80),
  sampWtMes = c(20, 50, 20, 120, 30)
)
print(CL)
#>      Year Quarter Country Species WeightKg ValueEUR
#>    <char>   <num>  <char>  <char>    <num>    <num>
#> 1:   2021       1      ZW     COD      100      300
#> 2:   2021       1      ZW     HKE       50      150
#> 3:   2021       2      ST     COD      200      600
#> 4:   2021       1      ST     COD      120      360
#> 5:   2022       2      ST     HKE       80      240
#> 6:   2022       2      YM     HKE       30      100
#> 7:   2021       1      YM     COD       10       50
#> 8:   2021       2      YM     HKE      100      150

print(CE)
#>      Year Quarter Country   Area NumDomTrip
#>    <char>   <num>  <char> <char>      <num>
#> 1:   2021       1      ZW   34.7       3500
#> 2:   2021       1      ZW   34.5        300
#> 3:   2021       2      ST   34.7       2010
#> 4:   2021       1      ST   34.5        500
#> 5:   2022       2      ST   34.5        250
#> 6:   2022       2      YM   34.7       2600
#> 7:   2021       1      YM   34.7       5000
#> 8:   2021       2      YM   34.5       1000

print(SA)
#>      Year Quarter Species CatchCategory totalWtMes sampWtMes
#>    <char>   <num>  <char>        <char>      <num>     <num>
#> 1:   2021       1     COD           Lan        100        20
#> 2:   2021       1     HKE           Lan         50        50
#> 3:   2021       2     COD           Dis         20        20
#> 4:   2022       1     COD           Lan        120       120
#> 5:   2022       2     HKE           Dis         80        30

1. Summarise a single numeric variable

The simplest use case of the function is to sum a numeric column by one grouping variable.


res_num <- amountByGroup(
data = CL,
var = "WeightKg",
valBy = "Year"
)
#> Returning numeric summary table.

res_num
#>      Year WeightKg
#>    <char>    <num>
#> 1:   2021      580
#> 2:   2022      110

This returns a data.table with total weight per year.

2. Summarise a single categorical variable

If the variable is non-numeric, amountByGroup() automatically computes frequency counts.


res_cat <- amountByGroup(
data = CL,
var = "Species",
valBy = "Year"
)
#> Returning frequency table for categorical variable.

res_cat
#>    Species   Year  Freq
#>     <char> <char> <int>
#> 1:     COD   2021     4
#> 2:     HKE   2021     2
#> 3:     HKE   2022     2

Each row represents a combination of categorical variable (Species) and the grouping variables (Year), with a frequency column (Freq).

3. Multiple numeric variables (wide table)

Multiple numeric variables can be summarise at once, producing a wide table.

Example with CL table:


CLres_multi_num <- amountByGroup(
data = CL,
var = c("WeightKg", "ValueEUR"),
valBy = c("Year", "Species")
)

CLres_multi_num
#>      Year Species WeightKg ValueEUR
#>    <char>  <char>    <num>    <num>
#> 1:   2021     COD      430     1310
#> 2:   2021     HKE      150      300
#> 3:   2022     HKE      110      340

Example with SA table:


SAres_multi_num <- amountByGroup(
data = SA,
var = c("totalWtMes", "sampWtMes"),
valBy = c("Species", "CatchCategory")
)

SAres_multi_num
#>    Species CatchCategory totalWtMes sampWtMes
#>     <char>        <char>      <num>     <num>
#> 1:     COD           Lan        220       140
#> 2:     HKE           Lan         50        50
#> 3:     COD           Dis         20        20
#> 4:     HKE           Dis         80        30

Each numeric variable is summed independently by the grouping variables.

4. Mixed numeric and categorical variables

Numeric and categorical variables can be supplied together.


res_mixed <- amountByGroup(
data = CE,
var = c("NumDomTrip", "Area"),
valBy = "Year"
)

str(res_mixed)
#> List of 2
#>  $ numeric    :Classes 'data.table' and 'data.frame':    2 obs. of  2 variables:
#>   ..$ Year      : chr [1:2] "2021" "2022"
#>   ..$ NumDomTrip: num [1:2] 12310 2850
#>   ..- attr(*, ".internal.selfref")=<pointer: 0x57f0dc85bbd0> 
#>  $ categorical:Classes 'data.table' and 'data.frame':    4 obs. of  3 variables:
#>   ..$ Year: chr [1:4] "2021" "2021" "2022" "2022"
#>   ..$ Area: chr [1:4] "34.7" "34.5" "34.5" "34.7"
#>   ..$ Freq: int [1:4] 3 3 1 1
#>   ..- attr(*, ".internal.selfref")=<pointer: 0x57f0dc85bbd0>

res_mixed
#> $numeric
#>      Year NumDomTrip
#>    <char>      <num>
#> 1:   2021      12310
#> 2:   2022       2850
#> 
#> $categorical
#>      Year   Area  Freq
#>    <char> <char> <int>
#> 1:   2021   34.7     3
#> 2:   2021   34.5     3
#> 3:   2022   34.5     1
#> 4:   2022   34.7     1

In this case, the function returns a list:

  • $numeric → summed numeric variables

  • $categorical → frequency tables for categorical variables

This keeps outputs explicit and avoids ambiguous table structures.

5. Applying filters

Filters are applied before summarising.


res_filtered <- amountByGroup(
data = CE,
var = "NumDomTrip",
valBy = "Country",
filters = list(Year = 2021)
)
#> Filter applied: 2021 in Year
#> Returning numeric summary table.

res_filtered
#>    Country NumDomTrip
#>     <char>      <num>
#> 1:      ZW       3800
#> 2:      ST       2510
#> 3:      YM       6000

Filters use standard %in% logic and may contain multiple values:


filters = list(Year = c(2021, 2022))

6. Percentages instead of absolute values

For numeric variables, results can be expressed as percentages of the total.

Example with SA table:


SA_res_pct <- amountByGroup(
data = SA,
var = "totalWtMes",
valBy = "CatchCategory",
asPct = TRUE
)
#> Returning numeric summary table.

SA_res_pct
#>    CatchCategory totalWtMes
#>           <char>      <num>
#> 1:           Lan   72.97297
#> 2:           Dis   27.02703

Example with CE table:


CE_res_pct <- amountByGroup(
data = CE,
var = "NumDomTrip",
valBy = "Area",
filters = list(Year=2021),
asPct = TRUE
)
#> Filter applied: 2021 in Year
#> Returning numeric summary table.

CE_res_pct
#>      Area NumDomTrip
#>    <char>      <num>
#> 1:   34.7   85.37774
#> 2:   34.5   14.62226

Percentages are computed per variable, not per group.

7. Plot output

Setting output_type = "plot" produces bar charts.

Example with SA table:


plot_SA <- amountByGroup(
data = SA,
var = "sampWtMes",
valBy = "Species",
output_type = "plot"
)

#> Plot generated for numerical variable.

plot_SA
#>    Species sampWtMes
#>     <char>     <num>
#> 1:     COD       160
#> 2:     HKE        80

Example with CE table:


plot_CE <- amountByGroup(
data = CE,
var = "NumDomTrip",
valBy = "Country",
output_type = "plot"
)

#> Plot generated for numerical variable.

plot_CE
#>    Country NumDomTrip
#>     <char>      <num>
#> 1:      ZW       3800
#> 2:      ST       2760
#> 3:      YM       8600

Notes:

  • Numeric variables → bar plot of summed values
  • Categorical variables → bar plot of frequencies
  • When multiple variables are supplied, one plot per variable is generated
  • Numeric variables → bar plot of summed value
  • Categorical variables → bar plot of frequencies
  • When multiple variables are supplied, one plot per variable is generated
  • The function still invisibly returns the underlying summary table

8. Plotting multiple variables

When output_type = "plot" and more than one variable is supplied in var, amountByGroup() produces one plot per variable, printed sequentially.

This applies to:

  • Multiple numeric variables
  • Mixed numeric + categorical variables

Each plot is generated independently to keep the output clear and interpretable.

8.1 Multiple numeric variables

When all variables in var are numeric, one bar plot is produced for each variable, using the same grouping variables.


plot_multi_numeric <- amountByGroup(
data = CL,
var = c("WeightKg", "ValueEUR"),
valBy = c("Year", "Country"),
output_type = "plot"
)

#> Plots generated for numeric and/or categorical variables.

plot_multi_numeric
#>      Year Country WeightKg ValueEUR
#>    <char>  <char>    <num>    <num>
#> 1:   2021      ZW      150      450
#> 2:   2021      ST      320      960
#> 3:   2022      ST       80      240
#> 4:   2022      YM       30      100
#> 5:   2021      YM      110      200

This results in:

  • One plot for WeightKg by Year (faceted by Country)
  • One plot for ValueEUR by Year (faceted by Country)

The plots are printed in sequence and the underlying summary table is still returned invisibly.

8.2 Mixed numeric and categorical variables

Numeric and categorical variables can be plotted together, and each variable is handled according to its type: * Numeric variables → summed bar plots * Categorical variables → frequency (count) bar plots


plot_mixed_var <- amountByGroup(
data = CL,
var = c("WeightKg", "Species"),
valBy = "Year",
output_type = "plot"
)

#> Plots generated for numeric and/or categorical variables.

plot_mixed_var
#> $numeric
#>      Year WeightKg
#>    <char>    <num>
#> 1:   2021      580
#> 2:   2022      110
#> 
#> $categorical
#>      Year Species  Freq
#>    <char>  <char> <int>
#> 1:   2021     COD     4
#> 2:   2021     HKE     2
#> 3:   2022     HKE     2

This produces: 1. A bar plot of total WeightKg by Year 2. A bar plot of counts of Species by Year

This explicit separation avoids mixing incompatible summaries in the same figure.

Faceting behaviour

When more than one grouping variable is supplied in valBy: * The first grouping variable is used on the x-axis * Additional grouping variables may be used for faceting (when applicable)

For example:


plot_facet <-  amountByGroup(
data = CE,
var = c("NumDomTrip"),
valBy = c("Country","Area"),
output_type = "plot"
)

#> Plot generated for numerical variable.

plot_facet
#>    Country   Area NumDomTrip
#>     <char> <char>      <num>
#> 1:      ZW   34.7       3500
#> 2:      ZW   34.5        300
#> 3:      ST   34.7       2010
#> 4:      ST   34.5        750
#> 5:      YM   34.7       7600
#> 6:      YM   34.5       1000

This produces a plot where: * xvar <- "Country" * facet_wrap(~ Area) is now applied * Result: one panel per Area , as expected

9. Assigning results to the global environment

For interactive workflows, results can be automatically assigned:


amountByGroup(
data = CL,
var = "WeightKg",
valBy = "Year",
assign_to_global = TRUE
)
#> Assigned table to global environment as: tbl_WeightKg_by_Year
#> Returning numeric summary table.

This creates an object named tbl_WeightKg_by_Year

Design philosophy

  • One table in, one summary out
  • No hidden joins or recoding
  • Explicit handling of numeric vs categorical variables
  • Predictable output structures
  • Predictable and reusable outputs

The function is intended as a final summarisation layer, not as a data preparation tool.

When not to use this function

  • When you need joins or code-to-label translations
  • When you need model-based summaries
  • When you need long-format reshaping for downstream modeling

In those cases, prepare the data first, then call amountByGroup().

Last review: 09/03/2026

#END