SAS (Base SAS)+
*==============================================================================;
* Sample data: subjects with missing dates and missing scores
*==============================================================================;
data adae;
infile datalines dlm='|' dsd missover;
length USUBJID $7 AESTDTC $10 RFSTDTC $10 TRTSDT $10;
input USUBJID AESTDTC RFSTDTC TRTSDT;
datalines4;
101-001|2024-03-15|2024-01-10|2024-01-12
101-002||2024-02-01|2024-02-03
101-003|||2024-03-05
101-004|2024-04-20|2024-03-10|
;;;;
run;
data scores;
infile datalines dlm='|' dsd missover;
input USUBJID : $7. SCORE1 SCORE2 SCORE3;
datalines4;
101-001|85|90|70
101-002|.|88|75
101-003|.|.|60
101-004|92|.|.
;;;;
run;
*==============================================================================;
* COALESCEC for character: pick first non-missing date
*==============================================================================;
data adae_derived;
set adae;
ASTDTC = coalescec(AESTDTC, RFSTDTC, TRTSDT);
run;
proc print data=adae_derived noobs;
title 'Character fallback: COALESCEC';
run;
*==============================================================================;
* COALESCE for numeric: pick first non-missing score
*==============================================================================;
data scores_derived;
set scores;
BEST_SCORE = coalesce(SCORE1, SCORE2, SCORE3);
run;
proc print data=scores_derived noobs;
title 'Numeric fallback: COALESCE';
run;- We create two datasets: ADAE with character date columns (some missing) and SCORES with numeric score columns (some missing).
- For character fallback, we use
COALESCEC(AESTDTC, RFSTDTC, TRTSDT). It walks left to right through the arguments and returns the first non-blank value. - For 101-001, AESTDTC is populated so COALESCEC returns it. For 101-002, AESTDTC is blank so it falls through to RFSTDTC. For 101-003, both are blank so it reaches TRTSDT.
- For numeric fallback, we use
COALESCE(SCORE1, SCORE2, SCORE3). It returns the first non-missing (non-dot) numeric value. - SAS requires that all arguments to COALESCE be numeric and all arguments to COALESCEC be character. Mixing types triggers a compile-time error.
- If all arguments are missing, both functions return missing — we see this nowhere in our sample data, but it is worth remembering for edge cases.
- After running, we check that each subject's derived column contains the correct fallback value based on which sources are populated.