SAS Day: The Cohort in SAS
SAS still runs a large share of Canadian health research. ICES and many agencies, hospitals and pharma groups have decades of SAS programs, and job postings ask for it. Today you meet SAS the way a new analyst usually does: with an extract for your cohort and a list of results to reproduce. You will write DATA steps with explicit types, BY-group processing for the two-claims rule, PROC SQL for joins and costs, PROC MEANS and PROC FREQ for Table 1, a macro, and an Excel report.
By the end of today you can
- SAS Studio runs, my
corridorfolder holds the extract, and%let pathpoints to it - read every file with a DATA step and explicit types, and I read the log after every run
- My BY-group program finds the same two-claims people as the expected results
- PROC MEANS, PROC FREQ and PROC SQL reproduce Table 1 and the Day 7 costs
- explain the PROC IMPORT leading-zero trap and why
put(din, 8.)does not fix it
Today's 5.5-hour plan
In this lesson
- 9.1 Set up SAS OnDemand for Academics
- 9.2 Build and upload the extract
- 9.3 DATA step: read with explicit types
- 9.4 BY-group processing: two claims within two years
- 9.5 Table 1 with PROC MEANS, PROC FREQ and PROC SQL
- 9.6 Costs with PROC SQL and a macro variable
- 9.7 PROC IMPORT and the leading zero
- 9.8 Mini-project: a macro and an Excel report
How to check your work today. SAS runs in SAS's cloud, not on your machine, so the course cannot run these programs for you. Instead,
day09/expected_results.pycomputes the result of every program from the same extract with DuckDB, and the course tests check that each program'sINPUTstatement matches the columns of the file it reads. Your SAS output should match the expected results. Money may differ in the last cent because of rounding.
9.1 Set up SAS OnDemand for Academics (35 min)
SAS OnDemand for Academics is free for learners and runs SAS Studio in your browser:
- Create a SAS profile and register for SAS OnDemand for Academics on SAS's website. Sign in and open SAS Studio.
- In the left pane, open Server Files and Folders, right-click Files (Home) → New → Folder, and name it
corridor. - Right-click the new folder → Properties, and copy its Location (something like
/home/u12345678/corridor). Every program starts with%let path = ...;: paste your location there.
SAS Studio has a program editor, a log and a results tab. Read the log after every run. SAS reports many problems as NOTEs and WARNINGs that let the program continue.
9.2 Build and upload the extract (25 min)
You don't upload the warehouse. Real analysts receive an extract: the cohort, plus the records needed for the analysis, as plain files with a documented layout. Build one:
"""Day 9.2: a small CSV extract to upload to SAS OnDemand for Academics (sas_extract/).
Researchers rarely get the whole database: they get an extract for their cohort.
Booleans are written as 0/1 and dates as YYYY-MM-DD, so SAS reads them without guessing.
"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import ROOT, warehouse # noqa: E402
out = os.path.join(ROOT, "sas_extract").replace("\\", "/")
os.makedirs(out, exist_ok=True)
con = warehouse()
cohort = os.path.join(ROOT, "warehouse", "cohort_base.parquet").replace("\\", "/")
con.execute(f"CREATE TEMP VIEW cohort AS SELECT * FROM read_parquet('{cohort}')")
con.execute("""
CREATE TEMP VIEW followup AS
SELECT c.person_id, c.province, c.index_date,
least(coalesce(p.death_date, DATE '2025-12-31'), DATE '2025-12-31') AS end_date,
(p.death_date IS NOT NULL AND p.death_date <= DATE '2025-12-31')::INT AS died
FROM cohort c JOIN dim_person p USING (person_id)""")
files = {
"cohort_base.csv": """
SELECT person_id, province, region, sex, age, income_quintile, rural::INT AS rural, index_date,
heart_failure::INT AS heart_failure, hypertension::INT AS hypertension, copd::INT AS copd,
prior_stays, physician_visits, nephrology_visit::INT AS nephrology_visit, metformin::INT AS metformin,
sglt2::INT AS sglt2, insulin::INT AS insulin, ace_inhibitor::INT AS ace_inhibitor,
statin::INT AS statin, drug_classes
FROM cohort ORDER BY person_id""",
"dx250_claims_2019_2024.csv": """
SELECT person_id, service_date FROM fct_physician_claims
WHERE dx_code = '250' AND service_date <= DATE '2024-12-31' ORDER BY claim_id""",
"cohort_followup.csv": """
SELECT person_id, province, index_date, end_date, died,
date_diff('day', index_date, end_date) + 1 AS days
FROM followup ORDER BY person_id""",
"cohort_cost_items.csv": """
SELECT x.person_id, x.cost_date, x.year, x.component, x.payer_cost
FROM int_cost_items x JOIN followup f USING (person_id)
WHERE x.cost_date BETWEEN f.index_date AND f.end_date
ORDER BY x.person_id, x.cost_date, x.component, x.payer_cost""",
"cpi_health.csv": "SELECT year, index AS cpi FROM stg_cpi_health ORDER BY year",
"cohort_drug_2025.csv": """
SELECT r.rx_id, r.person_id, r.dispense_date, r.din, r.plan_paid, r.total_cost
FROM fct_drug_dispensations r JOIN cohort USING (person_id)
WHERE r.dispense_year = 2025 ORDER BY r.rx_id""",
"drugs.csv": "SELECT din, product, ingredient, atc FROM stg_drugs ORDER BY din",
}
for name, sql in files.items():
con.execute(f"COPY ({sql}) TO '{out}/{name}' (HEADER, DELIMITER ',')")
n = con.sql(f"SELECT count(*) FROM ({sql})").fetchall()[0][0]
size = os.path.getsize(f"{out}/{name}") / 1e6
print(f"{name:<30}{n:>9,} rows {size:>7.1f} MB")
cohort_base.csv 6,224 rows 0.4 MB
dx250_claims_2019_2024.csv 490,984 rows 11.3 MB
cohort_followup.csv 6,224 rows 0.3 MB
cohort_cost_items.csv 240,341 rows 9.5 MB
cpi_health.csv 7 rows 0.0 MB
cohort_drug_2025.csv 170,988 rows 9.6 MB
drugs.csv 16 rows 0.0 MB
About 31 MB in seven files. Upload them all into your corridor folder (right-click the folder → Upload files). Booleans are written as 0/1 and dates as YYYY-MM-DD, so nothing has to be guessed.
9.3 DATA step: read with explicit types (40 min)
A SAS DATA step reads or changes data one row at a time. INFILE names the file, LENGTH fixes the text columns' widths, and INPUT lists every column in order, with $ for text and an informat such as :yymmdd10. for dates. A library (libname corr "&path";) is a folder of SAS datasets. corr.cohort is saved on disk, and work.x disappears when you sign out.
/* Day 9.3: read the extract with explicit types, then look at it.
Change the path to your folder: in SAS Studio, right-click the folder > Properties > Location. */
%let path = /home/u00000000/corridor;
libname corr "&path";
data corr.cohort;
infile "&path/cohort_base.csv" dsd firstobs=2 truncover;
length person_id $11 province $2 region $6 sex $1;
input person_id $ province $ region $ sex $ age income_quintile rural
index_date :yymmdd10. heart_failure hypertension copd prior_stays physician_visits
nephrology_visit metformin sglt2 insulin ace_inhibitor statin drug_classes;
format index_date yymmdd10.;
label rural = "Lives in a rural area (1 = yes)"
heart_failure = "Heart failure in the year before index (1 = yes)";
run;
proc contents data=corr.cohort varnum;
run;
proc freq data=corr.cohort;
tables province sex / nocum;
run;
Expected results (PROC FREQ):
=== 01_import.sas: PROC FREQ of province and sex
province frequency percent
ON 3956 63.56
QC 2268 36.44
sex frequency percent
F 2999 48.18
M 3225 51.82
PROC CONTENTS should list 20 variables: person_id, province, region and sex as character (Char), everything else as numeric (Num). SAS has only two types. A date is a number, the days since 1 January 1960, shown through a format such as yymmdd10..
9.4 BY-group processing: two claims within two years (45 min)
The Day 5 window function, in SAS's own idiom. Sort by person and date. A BY statement then gives you first.person_id on each person's first row. LAG() returns the previous row's value. RETAIN keeps a variable's value from one row to the next.
/* Day 9.4: "two physician claims within two years" (Day 5) with BY-group processing.
Run 01_import.sas first in the same session (it sets &path and the CORR library). */
data corr.dx250;
infile "&path/dx250_claims_2019_2024.csv" dsd firstobs=2;
length person_id $11;
input person_id $ service_date :yymmdd10.;
format service_date yymmdd10.;
run;
proc sort data=corr.dx250;
by person_id service_date;
run;
data corr.two_claims (keep=person_id case_date);
set corr.dx250;
by person_id;
retain found;
previous = lag(service_date); /* call LAG on every row, never inside an IF */
if first.person_id then do;
previous = .;
found = 0;
end;
if not found and previous ne . and service_date - previous <= 730 then do;
case_date = service_date; /* the second claim is the case date */
found = 1;
output;
end;
format case_date yymmdd10.;
run;
proc sql;
select count(*) as people format=comma10.,
min(case_date) as first_case format=yymmdd10.,
max(case_date) as last_case format=yymmdd10.
from corr.two_claims;
quit;
proc freq data=corr.two_claims;
tables case_date / nocum nopercent;
format case_date year4.;
run;
Expected results:
=== 02_two_claims.sas: people with two claims within 730 days, and case dates by year
people first_case last_case
32980 2019-01-01 2024-12-31
case_year frequency
2019 14570
2020 4198
2021 2943
2022 3175
2023 3852
2024 4242
This extract counts everyone with two claims, including people who died before 2025. Day 5's 28,110 counted only people alive on 31 December 2024. Two SAS traps to remember:
- Call
LAG()on every row.LAGreturns the value from the last time that line of code ran, not the previous row. Inside anIF, it skips rows and returns the wrong date, silently. - 2019 is inflated (14,570 case dates) for the same reason as Day 5.6: long-standing cases have their first two claims at the start of the data.
9.5 Table 1 with PROC MEANS, PROC FREQ and PROC SQL (30 min)
/* Day 9.5: the pieces of Table 1 (Day 6) with PROC MEANS, PROC FREQ and PROC SQL. */
proc means data=corr.cohort n mean std maxdec=1;
class province;
var age physician_visits drug_classes;
run;
proc freq data=corr.cohort;
tables province*(heart_failure sglt2 rural) / nocol nopercent;
run;
/* standardized difference for a 0/1 variable */
proc sql;
create table work.rural as
select mean(case when province = 'ON' then rural end) as p_on,
mean(case when province = 'QC' then rural end) as p_qc
from corr.cohort;
select p_on format=6.4, p_qc format=6.4,
(p_on - p_qc) / sqrt((p_on * (1 - p_on) + p_qc * (1 - p_qc)) / 2) as smd format=6.2
from work.rural;
quit;
Expected results:
=== 03_table_one.sas: PROC MEANS by province
province n age_mean age_std visits_mean classes_mean
ON 3956 79.3 8.5 11.3 4.0
QC 2268 79.1 8.4 11.3 3.9
PROC FREQ row percents (value = 1)
province heart_failure_pct sglt2_pct rural_pct
ON 15.29 41.66 11.83
QC 15.26 38.14 19.93
p_on p_qc smd
0.1183 0.1993 -0.22
PROC FREQ shows each cell's count with row percentages. The row percentage for value 1 is the share above. PROC SQL computes the standardized difference for rurality, the same −0.22 as Day 6.
9.6 Costs with PROC SQL and a macro variable (35 min)
SELECT ... INTO :cpi2025 stores a value in a macro variable. &cpi2025 then pastes it into later code as text. The cost query joins follow-up, cost items and the price index, inflates to 2025 dollars, and sums by person.
/* Day 9.6: follow-up costs (Day 7) - join, inflate to 2025 dollars, summarize. */
data corr.followup;
infile "&path/cohort_followup.csv" dsd firstobs=2;
length person_id $11 province $2;
input person_id $ province $ index_date :yymmdd10. end_date :yymmdd10. died days;
format index_date end_date yymmdd10.;
run;
data corr.cost_items;
infile "&path/cohort_cost_items.csv" dsd firstobs=2;
length person_id $11 component $9;
input person_id $ cost_date :yymmdd10. year component $ payer_cost;
format cost_date yymmdd10.;
run;
data corr.cpi;
infile "&path/cpi_health.csv" dsd firstobs=2;
input year cpi;
run;
/* the 2025 index into a macro variable */
proc sql noprint;
select cpi into :cpi2025 trimmed from corr.cpi where year = 2025;
quit;
%put NOTE: CPI 2025 = &cpi2025;
proc sql;
create table corr.fu_costs as
select f.person_id, f.province, f.days,
coalesce(sum(i.payer_cost * &cpi2025 / c.cpi), 0) as cost_2025
from corr.followup as f
left join corr.cost_items as i on i.person_id = f.person_id
left join corr.cpi as c on c.year = i.year
group by f.person_id, f.province, f.days;
title "Follow-up cost, 2025 dollars";
select province, count(*) as people,
sum(cost_2025) / count(*) as per_person format=dollar10.,
sum(cost_2025) / (sum(days) / 365.25) as per_person_year format=dollar10.
from corr.fu_costs
group by province;
select 'All' as province, count(*) as people,
sum(cost_2025) / count(*) as per_person format=dollar10.,
sum(cost_2025) / (sum(days) / 365.25) as per_person_year format=dollar10.
from corr.fu_costs;
title;
quit;
Expected results:
=== 04_costs.sas: follow-up cost per person and per person-year, 2025 dollars
province people per_person per_person_year
ON 3956 5397 5582
QC 2268 4795 4991
All 6224 5178 5368
These are Day 7's numbers ($5,582, $4,991 and $5,368 per person-year): three languages, one answer. SAS PROC SQL allows a GROUP BY with columns that are neither grouped nor summarized, and fills them in with a NOTE about "remerging". If you see that NOTE, check your GROUP BY.
9.7 PROC IMPORT and the leading zero (20 min)
Bug of the day. PROC IMPORT is the quick way to read a CSV: SAS guesses each column's type. It guesses that a DIN is a number.
/* Day 9 bug of the day: PROC IMPORT guesses types, and a DIN becomes a number. */
proc import datafile="&path/cohort_drug_2025.csv" out=work.rx_guess dbms=csv replace;
guessingrows=max;
run;
proc contents data=work.rx_guess varnum; /* din: Num - 09900066 is now 9900066 */
run;
/* a code list typed as text, the way formularies print DINs */
data work.sglt2;
length din $8;
input din $;
datalines;
09900066
09900074
;
run;
/* 1. joining a number to text: SAS stops with an ERROR about different data types */
proc sql;
select count(*) as matches from work.rx_guess as r inner join work.sglt2 as s on r.din = s.din;
quit;
/* 2. the tempting "fix" runs, but PUT(din, 8.) writes "9900066" with a leading blank, not "09900066" */
proc sql;
select count(*) as matches_put_8 from work.rx_guess as r
inner join work.sglt2 as s on put(r.din, 8.) = s.din;
quit;
/* 3. the real fix: read the DIN as text in the first place */
data work.rx;
infile "&path/cohort_drug_2025.csv" dsd firstobs=2;
length rx_id $12 person_id $11 din $8;
input rx_id $ person_id $ dispense_date :yymmdd10. din $ plan_paid total_cost;
format dispense_date yymmdd10.;
run;
proc sql;
select count(*) as sglt2_claims from work.rx as r inner join work.sglt2 as s on r.din = s.din;
quit;
Expected results:
=== 05_bug_proc_import.sas: SGLT2 claims in the cohort's 2025 drug extract
sglt2_claims_with_text_din
19306
matches_after_put_8
0
What happens at each step:
- PROC CONTENTS shows
dinas Num, and09900066is stored as 9900066 (Day 3's bug, in SAS). - Joining that number to a text code list stops with an ERROR: the expressions have different data types. At least SAS refuses loudly.
- The tempting fix,
put(r.din, 8.), runs without an error and matches 0 claims. It produces" 9900066", right-aligned with a blank where the zero was. (put(r.din, z8.)would restore the zero. Knowing that is good, but needing it is the warning sign.) - Reading
dinas$8text in a DATA step gives the 19,306 SGLT2 claims.
Rule: use PROC IMPORT to look at a file, and a DATA step with explicit types to read it.
9.8 Mini-project: a macro and an Excel report (30 min)
A SAS macro writes SAS code for you. %share(sglt2) generates the PROC SQL that summarizes one variable, and five calls build the table. ODS sends results to Excel, and PROC EXPORT writes a CSV.
/* Day 9 mini-project: a macro that adds one line per characteristic, and an Excel report. */
proc datasets lib=work nolist;
delete table1;
quit;
%macro share(var);
proc sql;
create table work._row as
select "&var" as characteristic length=20,
sum(case when province = 'ON' then &var else 0 end) as on_n,
mean(case when province = 'ON' then &var end) as on_pct format=percent8.1,
sum(case when province = 'QC' then &var else 0 end) as qc_n,
mean(case when province = 'QC' then &var end) as qc_pct format=percent8.1
from corr.cohort;
quit;
proc append base=work.table1 data=work._row force;
run;
%mend share;
%share(heart_failure)
%share(hypertension)
%share(copd)
%share(sglt2)
%share(insulin)
proc print data=work.table1 noobs;
run;
ods excel file="&path/table1_sas.xlsx" options(sheet_name="Table 1");
proc print data=work.table1 noobs;
run;
ods excel close;
proc export data=corr.fu_costs outfile="&path/fu_costs_sas.csv" dbms=csv replace;
run;
Expected results (table1_sas.xlsx, with the percentages shown as 15.3%):
=== 06_mini_project_report.sas: share with each condition or drug, by province
characteristic on_n on_pct qc_n qc_pct
heart_failure 605 15.3 346 15.3
hypertension 2789 70.5 1620 71.4
copd 238 6.0 154 6.8
sglt2 1648 41.7 865 38.1
insulin 1067 27.0 568 25.0
Try it (10 min). Without creating a new variable, count the cohort by age group (66–74, 75–84, 85+) and province. Use PROC FORMAT.
Solution
/* Day 9 exercise: age groups with PROC FORMAT - no new variable needed. */
proc format;
value agegrp 66-74 = '66-74'
75-84 = '75-84'
85-high = '85+';
run;
proc freq data=corr.cohort;
tables age*province / norow nocol nopercent;
format age agegrp.;
run;
Expected results:
=== 07_exercise_age_groups.sas: age groups by province (PROC FORMAT)
age_group ON QC
66-74 1318 762
75-84 1580 902
85+ 1058 604
A format changes how values are displayed and grouped, not the values themselves. That is why PROC FREQ can group ages into three bands without a new column.
9.9 Save your work
Download your programs from SAS Studio (right-click → Download) into day09/sas/, then commit. The extract is generated, so keep sas_extract/ out of Git.
def sas_inputs():
"""(csv file, variables in the INPUT statement) for every DATA step that reads a CSV."""
found = []
for name in sorted(os.listdir(SAS)):
text = open(os.path.join(SAS, name), encoding="utf-8").read()
for m in re.finditer(r'infile\s+"&path/([\w.]+)".*?;\s*(?:length[^;]*;\s*)?input\s+([^;]*);', text, re.S | re.I):
tokens = [t for t in m.group(2).split() if not t.startswith(":") and t != "$" and not t.endswith(".")]
found.append((name, m.group(1), [t.lower() for t in tokens]))
return found
@pytest.mark.skipif(not os.path.exists(EXTRACT), reason="build the SAS extract first (Day 9)")
@pytest.mark.parametrize("program,file,variables", sas_inputs())
def test_sas_input_matches_csv_header(program, file, variables):
with open(os.path.join(EXTRACT, file), newline="", encoding="utf-8") as f:
header = [h.lower() for h in next(csv.reader(f))]
assert variables == header, f"{program} reads {file} with the wrong columns"
python -m pytest -q
git add .
git commit -m "Day 9: the cohort in SAS"
Day 9 checklist
- SAS Studio runs, my
corridorfolder holds the extract, and%let pathpoints to it - I read every file with a DATA step and explicit types, and I read the log after every run
- My BY-group program finds the same two-claims people as the expected results
- PROC MEANS, PROC FREQ and PROC SQL reproduce Table 1 and the Day 7 costs
- I can explain the PROC IMPORT leading-zero trap and why
put(din, 8.)does not fix it
Bloc français (30 min)
Thème : un extrait de données et un programme SAS.
Le chercheur ne reçoit pas toute la base de données, mais un extrait limité à sa cohorte. Il lit chaque fichier avec une étape DATA en précisant le type de chaque variable. Avant d'analyser les résultats, il consulte toujours le journal, car SAS signale plusieurs problèmes par de simples avertissements. Une macro permet de répéter le même calcul pour plusieurs variables sans copier le code.
| Français | English |
|---|---|
| un extrait de données | a data extract |
| la base de données | the database |
| une étape DATA | a DATA step |
| une procédure | a procedure (PROC) |
| le journal | the log |
| un avertissement | a warning |
| une erreur | an error |
| le type (numérique, caractère) | the type (numeric, character) |
| un format | a format |
| une macro, une variable macro | a macro, a macro variable |
| un rapport | a report |
| télécharger, téléverser | to download, to upload |
Exercices
- Translate: "Read the log after every run."
- Translate: « PROC IMPORT a lu le DIN comme un nombre, et le zéro initial a disparu. »
- In three French sentences, explain what a SAS format does in the age-group exercise.
Réponses
- Lisez le journal après chaque exécution.
- "PROC IMPORT read the DIN as a number, and the leading zero disappeared."
- Example: Un format change la façon d'afficher et de regrouper les valeurs, sans les modifier. Avec le format agegrp., PROC FREQ regroupe les âges en trois tranches. On n'a donc pas besoin de créer une nouvelle variable.