TEAE Summary Table in SAS and R: Subjects vs Events by SOC and PT

By Mohan Peddineni · · 1 min read
In a TEAE summary table, each cell counts subjects, not events. A subject with three headaches counts once for Headache and once for its system organ class. The denominator is the number of subjects in the safety population for that arm, taken from ADSL, not from ADAE. Most QC mismatches on this table break one of those two rules.

The adverse event summary by system organ class (SOC) and preferred term (PT) is one of the first tables a new clinical programmer is given. It looks simple: count the AEs, add percentages. Then the independent QC programmer gets different numbers, and nobody can say which side is right.

This post builds the table step by step in SAS and R from a small dataset you can check by hand. It covers the counting rules, the denominator, zero rows and sort order, then lists the mismatches that come up again and again in real QC.

The counting rules

  • Count subjects, not records. Each cell is the number of distinct subjects with at least one event at that level.
  • One subject, one count per row. A subject with Nausea and Vomiting counts once in the Gastrointestinal disorders row, even with two different terms.
  • Only treatment-emergent events. Use TRTEMFL = "Y" in ADAE. Events before first dose are not TEAEs.
  • Denominator from ADSL. Big N per arm is the number of subjects in the safety population (SAFFL = "Y"), by actual treatment. Subjects with no AEs still count in N.
  • Show every arm on every row. If no subject in an arm had the term, the cell shows 0, not a blank or a missing row.

The SAP or the table shell can change details, such as sort order, whether to show event counts as well or whether the "Any TEAE" row comes first. The subject-counting rule itself almost never changes.

The example data

Eight subjects in the safety population, four per arm. Subject S04 has one AE that started before first dose, so it is not treatment-emergent. S03 and S08 had no AEs at all, so they only appear in ADSL.

ADSL (one record per subject)

USUBJIDTRT01ATRT01ANSAFFL
S01Placebo1Y
S02Placebo1Y
S03Placebo1Y
S04Placebo1Y
S05Drug A2Y
S06Drug A2Y
S07Drug A2Y
S08Drug A2Y

ADAE (one record per adverse event)

USUBJIDTRTANAEBODSYSAEDECODTRTEMFL
S011Nervous system disordersHeadacheY
S011Nervous system disordersHeadacheY
S021Gastrointestinal disordersNauseaY
S041Nervous system disordersDizzinessN
S052Gastrointestinal disordersNauseaY
S052Gastrointestinal disordersVomitingY
S062Gastrointestinal disordersNauseaY
S062Nervous system disordersHeadacheY
S072Nervous system disordersHeadacheY

The code below uses these variable names, so it runs on your own ADSL and ADAE as they are. In R the variables are upper case, as they come from haven::read_xpt().

The expected table

Work it out by hand before writing code. Arm 1 is Placebo, arm 2 is Drug A, and N = 4 in each arm.

System organ class / Preferred termPlacebo (N=4) n (%)Drug A (N=4) n (%)
Any TEAE2 (50.0)3 (75.0)
Gastrointestinal disorders1 (25.0)2 (50.0)
  Nausea1 (25.0)2 (50.0)
  Vomiting01 (25.0)
Nervous system disorders1 (25.0)2 (50.0)
  Headache1 (25.0)2 (50.0)

Check the tricky cells:

  • Placebo, Headache = 1, not 2. S01 had two Headache records, but S01 is one subject.
  • Placebo, Nervous system disorders = 1. S04's Dizziness started before treatment, so it is excluded. That is also why Dizziness has no row.
  • Drug A, Gastrointestinal disorders = 2, not 3. S05 had Nausea and Vomiting, but counts once for the SOC.
  • Placebo, Any TEAE = 2 of 4. S03 and S04 had no TEAE, but they are still in the denominator.
  • Sort order: SOCs by total subjects, highest first (both have 3 here, so alphabetical breaks the tie), then PTs within each SOC the same way. Use whatever order your SAP specifies.

Step 1: denominators and distinct-subject counts

Count distinct subjects at three levels: any TEAE, SOC, and SOC with PT. Then cross every row with every arm so zero cells exist as rows, and format n (%).

proc sql;
  /* Big N per actual treatment arm */
  create table bign as
  select trt01an as trtan,
         count(distinct usubjid) as bign
    from adsl
    where saffl = 'Y'
    group by trt01an;

  /* TEAEs in the safety population */
  create table teae as
  select *
    from adae
    where trtemfl = 'Y'
      and usubjid in
          (select usubjid from adsl
            where saffl = 'Y');

  /* distinct subjects at each level */
  create table counts as
  select 1 as lvl,
         ' ' as aebodsys length=40,
         'Any TEAE' as term length=40,
         trtan,
         count(distinct usubjid) as n
    from teae
    group by trtan
  union all
  select 2, aebodsys, aebodsys, trtan,
         count(distinct usubjid)
    from teae
    group by aebodsys, trtan
  union all
  select 3, aebodsys, aedecod, trtan,
         count(distinct usubjid)
    from teae
    group by aebodsys, aedecod, trtan;

  /* every row x every arm: keeps zeros */
  create table frame as
  select t.lvl, t.aebodsys, t.term,
         b.trtan, b.bign
    from (select distinct lvl, aebodsys, term
            from counts) as t,
         bign as b;

  create table cells as
  select f.*, coalesce(c.n, 0) as n,
         100 * calculated n / f.bign as pct,
         case when calculated n = 0 then '0'
              else catx(' ',
                put(calculated n, 3.),
                cats('(',
                  put(calculated pct, 5.1),
                  ')'))
         end as cell length=20
    from frame as f
    left join counts as c
      on  f.lvl      = c.lvl
      and f.aebodsys = c.aebodsys
      and f.term     = c.term
      and f.trtan    = c.trtan;
quit;
library(dplyr)
library(tidyr)

# Big N per actual treatment arm
bign <- adsl %>%
  filter(SAFFL == "Y") %>%
  count(TRTAN = TRT01AN, name = "BIGN")

# TEAEs in the safety population
saf <- filter(adsl, SAFFL == "Y")
teae <- adae %>%
  filter(TRTEMFL == "Y") %>%
  semi_join(saf, by = "USUBJID")

# distinct subjects per group
subj <- function(d, ...) {
  d %>%
    group_by(TRTAN, ...) %>%
    summarise(n = n_distinct(USUBJID),
              .groups = "drop")
}

# distinct subjects at each level
counts <- bind_rows(
  subj(teae) %>%
    mutate(lvl = 1, AEBODSYS = "",
           term = "Any TEAE"),
  subj(teae, AEBODSYS) %>%
    mutate(lvl = 2, term = AEBODSYS),
  subj(teae, AEBODSYS, AEDECOD) %>%
    mutate(lvl = 3, term = AEDECOD) %>%
    select(-AEDECOD)
)

# every row x every arm: keeps zeros
keys <- c("lvl", "AEBODSYS", "term", "TRTAN")
cells <- counts %>%
  distinct(lvl, AEBODSYS, term) %>%
  crossing(bign) %>%
  left_join(counts, by = keys) %>%
  mutate(
    n    = coalesce(n, 0L),
    pct  = 100 * n / BIGN,
    cell = sprintf("%d (%.1f)", n, pct),
    cell = if_else(n == 0, "0", cell)
  )

count(distinct usubjid) in SAS and n_distinct(USUBJID) in R are what make this a subject count. Replace them with count(*) or n() and you get event counts, which is the most common error on this table.

Step 2: sort and lay out the table

/* sort keys: subject totals per SOC, PT */
proc sql;
  create table soctot as
  select aebodsys, sum(n) as socn
    from cells
    where lvl = 2
    group by aebodsys;

  create table pttot as
  select aebodsys, term, sum(n) as ptn
    from cells
    where lvl = 3
    group by aebodsys, term;

  create table sorted as
  select c.lvl, c.aebodsys, c.term,
         c.trtan, c.cell, s.socn, p.ptn,
         (c.lvl > 1) as notany
    from cells as c
    left join soctot as s
      on c.aebodsys = s.aebodsys
    left join pttot as p
      on  c.aebodsys = p.aebodsys
      and c.term     = p.term
    order by notany, socn desc, aebodsys,
             lvl, ptn desc, term, trtan;
quit;

data sorted;
  set sorted;
  by lvl aebodsys term notsorted;
  if first.term then ord + 1;
run;

proc transpose data=sorted
               out=aetable(drop=_name_)
               prefix=trt;
  by ord lvl aebodsys term;
  id trtan;
  var cell;
run;

proc report data=aetable nowd split='|';
  column lvl term trt1 trt2;
  define lvl  / display noprint;
  define term / display
         'System organ class|Preferred term';
  define trt1 / display 'Placebo|(N=4)';
  define trt2 / display 'Drug A|(N=4)';
  compute term;
    if lvl = 3 then
      call define(_col_, 'style',
                  'style=[leftmargin=12pt]');
  endcomp;
run;
aetable <- cells %>%
  group_by(AEBODSYS) %>%
  mutate(soc_n = sum(n[lvl == 2])) %>%
  group_by(AEBODSYS, term) %>%
  mutate(pt_n = sum(n)) %>%
  ungroup() %>%
  arrange(lvl > 1, desc(soc_n), AEBODSYS,
          lvl, desc(pt_n), term) %>%
  select(lvl, term, TRTAN, cell) %>%
  pivot_wider(names_from = TRTAN,
              values_from = cell,
              names_prefix = "trt") %>%
  mutate(term = if_else(lvl == 3,
                        paste0("  ", term),
                        term)) %>%
  select(-lvl)

aetable

Both give the table above. In production, take the column headers from bign (a macro variable in SAS, or glue() in R) rather than typing N=4, so the header can't disagree with the denominator.

Where the numbers come from in ADaM

ADAE follows the ADaM Occurrence Data Structure (OCCDS). It can carry first-occurrence flags: AOCCFL (first occurrence of any event for the subject), AOCCSFL (first occurrence within the SOC) and AOCCPFL (first occurrence of the PT). If your ADAE has them, counting records where AOCCPFL = "Y" gives the same subject counts as n_distinct().

There is one catch. The flags are only correct for this table if they were derived on the treatment-emergent records. If the first Headache for a subject was pre-treatment and the flag sits on that record, filtering on TRTEMFL = "Y" and AOCCPFL = "Y" drops the subject. When in doubt, count distinct subjects directly. It is never wrong.

Variations you will be asked for

Once the main table works, most of the other AE summaries in a safety package are the same program with one extra filter on teae. The variable names below are the usual ones. Check your ADaM spec and the SAP for the exact rule.

TableExtra filter
Serious TEAEsAESER = "Y"
Related TEAEsThe SAP's relatedness rule, for example AREL = "RELATED"
TEAEs leading to discontinuation of study drugAEACN = "DRUG WITHDRAWN"
Grade 3 or higherATOXGR in ("3", "4", "5")
TEAEs with a fatal outcomeAESDTH = "Y"

Keep the denominator the same: Big N is still every subject in the safety population, not only subjects with a serious or related event.

By maximum severity

A severity table counts each subject once per row, at the worst severity they had for that term. If S01's two Headache records were Mild and Moderate, S01 counts once, under Moderate, and not under Mild. Take the maximum per subject first, then count:

/* worst severity per subject and PT */
proc sql;
  create table worst as
  select trtan, aebodsys, aedecod,
         usubjid,
         max(asevn) as asevn
    from teae
    group by trtan, aebodsys,
             aedecod, usubjid;

  create table bysev as
  select trtan, aebodsys, aedecod,
         asevn,
         count(distinct usubjid) as n
    from worst
    group by trtan, aebodsys,
             aedecod, asevn;
quit;
# worst severity per subject and PT
worst <- teae %>%
  group_by(TRTAN, AEBODSYS, AEDECOD,
           USUBJID) %>%
  summarise(ASEVN = max(ASEVN),
            .groups = "drop")

bysev <- worst %>%
  count(TRTAN, AEBODSYS, AEDECOD,
        ASEVN, name = "n")

For the SOC rows, do the same without aedecod in the GROUP BY. Decide up front how to handle a missing severity: many SAPs count it as the most severe category, so it is never silently dropped. Use the numeric ASEVN, not the text. Mild, Moderate and Severe only give the right maximum because they happen to be in alphabetical order. A value such as "LIFE THREATENING" sorts before "MILD", so the text maximum would quietly pick the wrong category.

Why your table doesn't match QC: the usual causes

  • Events counted instead of subjects. Placebo Headache shows 2 instead of 1. Look for count(*), n() or PROC FREQ on the event-level dataset.
  • Denominator taken from ADAE. Placebo has three subjects in ADAE (S01, S02, S04) but four in the safety population, so 1/3 = 33.3% instead of 1/4 = 25.0%.
  • TRTEMFL not applied. S04's pre-treatment Dizziness appears, and Placebo Nervous system disorders becomes 2.
  • Planned instead of actual treatment. Safety tables use the treatment received. A subject randomised to Placebo who got Drug A in error moves column.
  • Zero rows missing. Placebo Vomiting disappears or shows blank because the program never created the zero cell.
  • Sort order. Alphabetical vs descending frequency, and frequency in which arm. Both programmers need to read the same line of the SAP.
  • Rounding on exact ties. SAS formats round 6.25 up to 6.3. R's sprintf() uses C rounding, which can give 6.2 for the same value. If both sides use different languages, agree on a rounding rule and test a tie value.
  • Uncoded or recoded terms. A missing AEDECOD or a MedDRA version upgrade between data cuts changes which row an event lands in.

Self-checks before you hand it to QC

These checks take a few minutes and catch most counting errors before the independent programmer does:

  • Any TEAE is never more than N for its arm.
  • No PT count is higher than its SOC count. A subject with the PT always has the SOC.
  • No SOC count is higher than the sum of its PT counts, and no SOC is higher than Any TEAE.
  • Any TEAE equals the distinct subjects in your teae dataset for that arm.
  • Recompute one percentage by hand from n and N, including a zero row.

The second check as code. It should return no rows:

/* no PT count above its SOC count */
proc sql;
  select p.trtan, p.term, p.n,
         s.n as socn
    from counts(where=(lvl=3)) as p
    join counts(where=(lvl=2)) as s
      on  p.aebodsys = s.aebodsys
      and p.trtan    = s.trtan
    where p.n > s.n;
quit;
# no PT count above its SOC count
pt  <- filter(counts, lvl == 3)
soc <- filter(counts, lvl == 2)

pt %>%
  inner_join(soc,
             by = c("TRTAN", "AEBODSYS"),
             suffix = c("", "_soc")) %>%
  filter(n > n_soc)
Try it yourself: add one subject

Subject S09 joins Drug A and is in the safety population. S09 has one AE: Headache, TRTEMFL = "N" (it started before first dose). Which cells in the Drug A column change, and what are the new values?

Answer: S09 adds no TEAE, so no count changes. But Big N for Drug A becomes 5, so every percentage changes: Any TEAE 3 (60.0), Gastrointestinal disorders 2 (40.0), Nausea 2 (40.0), Vomiting 1 (20.0), Nervous system disorders 2 (40.0), Headache 2 (40.0), and the header becomes N=5. If your counts went up, the TRTEMFL filter is missing. If your percentages did not move, the denominator is coming from ADAE.

Quick check

1. A subject has Nausea twice and Vomiting once, all treatment-emergent. How many times is the subject counted in the Gastrointestinal disorders row?

Each row counts distinct subjects. The subject also counts once in the Nausea row and once in the Vomiting row.

2. Where does the denominator for the percentages come from?

Subjects with no adverse events are still part of the population at risk, and they only exist in ADSL.

3. An AE started the day before first dose (TRTEMFL = "N"). Where does it appear in the TEAE table?

The table is limited to treatment-emergent events. Pre-treatment events belong in medical history or a separate listing, if the SAP asks for one.

Frequently asked questions

What is a TEAE?

A treatment-emergent adverse event: one that starts on or after first dose, or an existing condition that gets worse after first dose. The exact window is defined in the SAP and stored in ADAE as TRTEMFL = "Y".

Should the AE table show events as well as subjects?

Some shells add an event count column, written as n (%) [E]. The subject count and percentage are still the main numbers. If you add events, count records, and label the column so readers can tell them apart.

Which population is used for AE tables?

Usually the safety population, by actual treatment received. Check the SAP: some studies define it differently.

How do I count AEs by maximum severity?

Take the worst severity per subject for each term first (use the numeric ASEVN), then count distinct subjects at that severity. Each subject appears once per row.

How do I sort SOCs and PTs?

Common choices are descending frequency in the total or in the active arm, or alphabetical. Use the SAP's rule and break ties alphabetically so both programmers get the same order.

Key takeaways
  • Each cell counts distinct subjects: count(distinct usubjid) in SAS, n_distinct() in R.
  • Big N comes from ADSL (safety population, actual treatment), never from ADAE.
  • Filter on TRTEMFL = "Y" before counting, and check first-occurrence flags were derived on TEAEs.
  • Build every row for every arm so zero cells show as 0.
  • Serious, related and severity tables reuse the same program: add a filter, or take the worst severity first.
  • Agree sort order and rounding with QC before either side starts.

Related: CDISC for programmers: one adverse event from the CRF to the table · ADaM explained · PROC REPORT page breaks and column widths · More TLF articles

MP
Written by Mohan Peddineni

Manager, Statistical Programming. Writes about SAS, R, CDISC and regulatory submissions. More about me → · LinkedIn

Comments

↑