Skip to main content

10  Computed columns and summaries

The examples use one raven of patients, whose ward is a factor in the order of the hospital’s floors, with one ward not recorded and two readings of blood pressure missing:

vitals
<raven table> 8 rows ⨉ 6 columns
   ward        sex            age  weight  height     sbp
   factor      character  integer  double  double  double
                           [year]    [kg]     [m]  [mmHg]
   1 NA                                              2 NA
1  ICU         F               71    62.1    1.62     142
2  Cardiology  M               58    88.4    1.80     128
3  ICU         M               64    79.0    1.75      NA
4  Oncology    F               49    55.3    1.58     118
5  Cardiology  F               77    70.2    1.65     151
6  NA          M               35    92.5    1.88     122
7  ICU         F               82    58.8    1.55     160
8  Oncology    M               60    81.6    1.77      NA

10.1 An expression is a value

calc() holds an expression of the rule dialect, as rule() holds a condition. A bare name is a column, val() the value of an R expression, and col() the column whose name an R expression gives:

calc(weight / height^2)
<r8 calc> weight/height^2
m <- "sbp"
calc(mean(col(m), na.rm = TRUE))
<r8 calc> mean(sbp, na.rm = TRUE)

The expression is compiled against the columns of the table it is given with, and evaluated in Rust, with the same result in every host language.

10.2 Computed columns

r8set() takes calc() values among its columns, computed over the rows of the table as given. A result has the unit that the expression infers: a difference of millimeters of mercury is in mmHg, and a quotient has none until it is stated:

v <- r8set(vitals, list(bmi = calc(weight / height^2)))
v <- r8annotate(v, unit = c(bmi = "kg/m^2"))
v[c("weight", "height", "bmi")]
<raven table> 8 rows ⨉ 3 columns
   weight  height       bmi
   double  double    double
     [kg]     [m]  [kg/m^2]
1    62.1    1.62     23.66
2    88.4    1.80     27.28
3    79.0    1.75     25.80
4    55.3    1.58     22.15
5    70.2    1.65     25.79
6    92.5    1.88     26.17
7    58.8    1.55     24.47
8    81.6    1.77     26.05

An aggregate in a computed column is over all rows, or, with by, over the rows of each row’s group:

r8set(vitals, list(n_ward = calc(n()), excess = calc(sbp - mean(sbp, na.rm = TRUE))), by = "ward")
<raven table> 8 rows ⨉ 8 columns
   ward        sex            age  weight  height     sbp   n_ward  excess
   factor      character  integer  double  double  double  integer  double
                           [year]    [kg]     [m]  [mmHg]           [mmHg]
   1 NA                                              2 NA             2 NA
1  ICU         F               71    62.1    1.62     142        3    -9.0
2  Cardiology  M               58    88.4    1.80     128        2   -11.5
3  ICU         M               64    79.0    1.75      NA        3      NA
4  Oncology    F               49    55.3    1.58     118        2     0.0
5  Cardiology  F               77    70.2    1.65     151        2    11.5
6  NA          M               35    92.5    1.88     122        1     0.0
7  ICU         F               82    58.8    1.55     160        3     9.0
8  Oncology    M               60    81.6    1.77      NA        2      NA

NA is the missing constant of the dialect, and an error in a row, such as a division by zero, is an error that counts the rows:

r8set(vitals, list(per_year = calc(weight / (age - age))))
Error:
! `per_year` has no value in row 1: division by zero; nor in 7 other rows.

10.3 Summaries of groups

r8summarize() gives one row for each group of the rows by the key columns by: the keys, then the summaries, each a calc() of aggregates:

r8summarize(
  vitals,
  list(
    n = calc(n()),
    sbp = calc(mean(sbp, na.rm = TRUE)),
    age = calc(median(age))
  ),
  by = "ward"
)
<raven table> 4 rows ⨉ 4 columns
   ward              n     sbp     age
   factor      integer  double  double
                        [mmHg]  [year]
   1 NA
1  ICU               3   151.0    71.0
2  Cardiology        2   139.5    67.5
3  Oncology          2   118.0    54.5
4  NA                1   122.0    35.0

Groups are in the order of r8sort() of the keys: ascending, missing last, strings by code point, and factors by level. The key columns keep their kinds, levels, units, and descriptions. Without by, the summary is one row:

r8summarize(vitals, list(n = calc(n()), weight = calc(sum(weight)), heavy = calc(count(weight > 80))))
<raven table> 1 row ⨉ 3 columns
         n  weight    heavy
   integer  double  integer
              [kg]
1        8   587.9        3

The aggregates are n(), count(cond), sum(), mean(), median(), min(), and max(), alone or in an expression, such as a mean weighted by another column, calc(sum(w * x) / sum(w)). sum() is the exact sum, rounded once, so that the result does not depend on the order of the rows.

10.4 Typed functions

A summary that the dialect has no word for is a typed function, called inside calc() once for each group. A parameter of vec(T) takes the cells of its argument in the rows of the group, and a scalar parameter takes a constant or val():

trimmed_mean <- new_function(
  "trimmed_mean",
  function(x = arg_vec(type_double()), trim = arg_double(default = 0)) {
    mean(x, trim = trim)
  },
  return_type = type_double()
)
r8summarize(vitals, list(weight = calc(trimmed_mean(weight, trim = 0.25))), by = "sex")
<raven table> 2 rows ⨉ 2 columns
   sex        weight
   character  double
1  F           60.45
2  M           85.00

The function returns one value of a scalar type, which has no unit. A call is a term of the expression, as an aggregate is, and a term without a unit takes the unit of the term it is added to, so that weight - trimmed_mean(weight) is in kg. In r8set(), each row takes the value of its group:

r8set(vitals, list(above = calc(weight - trimmed_mean(weight))), by = "sex")[c("sex", "weight", "above")]
<raven table> 8 rows ⨉ 3 columns
   sex        weight   above
   character  double  double
                [kg]    [kg]
1  F            62.1   0.500
2  M            88.4   3.025
3  M            79.0  -6.375
4  F            55.3  -6.300
5  F            70.2   8.600
6  M            92.5   7.125
7  F            58.8  -2.800
8  M            81.6  -3.775

Each call is checked as a direct call: a group with a missing cell for a parameter of vec(T) is the call’s error, with the group’s keys, and a parameter of vec(option(T)) receives the missing cells. The functions of the dialect come first, so that mean() is always the dialect’s exact mean, and an R function that is not a typed function is an error:

r8summarize(vitals, list(sbp = calc(trimmed_mean(sbp))), by = "sex")
Error:
! r8summarize(): `sbp` calls `demo::trimmed_mean()` in the group sex = "M": Invalid arguments of `trimmed_mean()`: 1 problem
- `x[[2]]` must be a value. Also at x[[4]]. [missing_value]
calc(stats::sd(weight))
Error:
! `stats::sd(weight)`: `stats::sd()` is an R function; calc() calls the functions of the dialect and typed functions of new_function(), such as new_function("f", function(x = arg_vec(type_double())) ..., return_type = type_double()).

The calls of a function whose body is in Rust run from R8’s Rust code, without R, through the same expression (Moving a function to Rust).

10.5 Missing cells

An aggregate over a missing cell is missing, as in R. na.rm = TRUE in the aggregate leaves out the missing cells:

r8summarize(vitals, list(all = calc(mean(sbp)), recorded = calc(mean(sbp, na.rm = TRUE))), by = "ward")
<raven table> 4 rows ⨉ 3 columns
   ward           all  recorded
   factor      double    double
               [mmHg]    [mmHg]
   1 NA          2 NA
1  ICU             NA     151.0
2  Cardiology   139.5     139.5
3  Oncology        NA     118.0
4  NA           122.0     122.0

A summary reads cells within aggregates; a column of every row is r8set()’s:

r8summarize(vitals, list(older = calc(age + 1)))
Error:
! `older` does not fit the table: a summary reads the cells of its columns within aggregates, such as `mean(x)`; `r8set()` computes a column of every row.

10.6 Threads

The work in Rust of r8summarize(), r8set(), r8map(), r8sort(), r8filter(), and r8check() runs on up to n_threads threads, whose default is the option r8.n_threads: half the logical cores, at most 2 where R CMD check limits the cores. The sums are exact, so a result is the same for any number of threads:

identical(
  r8summarize(vitals, list(w = calc(sum(weight))), by = "ward", n_threads = 1L),
  r8summarize(vitals, list(w = calc(sum(weight))), by = "ward", n_threads = 2L)
)
[1] TRUE
© 2026 E.D. Gennatas