29  SAS for R Programmers

R-only graduates of this program have reported being screened out of industry positions before an interview, because the application asked for SAS. That failure is at least visible. The quiet one comes after you are hired. A SAS program and an R program fit ‘the same model’ to the same data and report different numbers. The two languages chose different defaults (a reference level, a coding scheme, a censoring code, a method for tied event times), and neither said so. This chapter gives you enough SAS to read a program and its log, and to move data across the boundary without losing anything. It also shows how to reproduce the procedures that fill most clinical study reports. A table lists the defaults you must set on both sides before the numbers agree.

The determined Real Programmer can write FORTRAN programs in any language.

Ed Post, Real Programmers Don’t Use Pascal (1983)

Diagram of the analysis pipeline: six stages in order (Plan, Acquire, Wrangle, Analyze, Report, Share) above two bands that run under every stage (Version control and Environment). Highlighted for this chapter: Analyze.
Figure 29.1: Where this chapter sits: fitting and checking models in a second language is part of the Analyze stage.
NoteIn this chapter

Reading time. About 40 minutes.

You’ll need. Chapter 28 for the HF-HOME ADSL and ADTTE datasets this chapter reuses, and Chapter 18 for row-count checks. The R code uses:

No SAS installation is needed. Every SAS block in this chapter is display-only and has not been run for this edition. The R code beside it runs.

You’ll be able to.

  • Read a short SAS program, distinguishing DATA steps from PROC steps, and write its R equivalent.
  • Predict where an R and a SAS fit of the same model will disagree, from the defaults that differ, and set both sides so that they agree.
  • Read a SAS log and name the NOTE that signals lost or multiplied data.
  • Move analysis datasets between R and SAS as transport files and verify names, types, labels, and dates after each crossing.

Outline.

If these answers come quickly, skip to the next chapter. The answers are in Section 29.12.

  1. What is the DATA step in SAS, and what is its relationship to PROC steps?
  2. Given a SAS dataset work.demo, what SAS procedure and what R function would each produce a summary of continuous variables analogous to R’s summary()?
  3. What file format is typically used to move datasets between SAS and non-SAS systems (including R), and what R package reads it?

29.1 Where SAS is required, and where it is not

A regulatory submission to the United States Food and Drug Administration (FDA) requires its datasets in SAS XPORT (XPT version 5) transport format, structured to CDISC (Clinical Data Interchange Standards Consortium) standards as the FDA Data Standards Catalog specifies. XPT is an open, documented format that R writes as readily as SAS does. FDA does not require SAS software. Its Statistical Software Clarifying Statement (2015) says sponsors may use any suitable software. R Consortium pilots have since carried R-based submission packages through FDA review (Section 28.5). Nevertheless, SAS remains the incumbent in sponsors and contract research organizations (CROs). It is therefore what most industry teams expect you to read and write.

The division between sectors follows the deliverable rather than the merits of the languages. Where the deliverable is a regulatory artifact, changing tools means revalidating a pipeline a regulator has already accepted. It also means retraining a department audited on its documented procedures. That cost keeps SAS in most sponsor-driven trials, much CRO work, and many government agencies. Where the deliverable is a paper, the ecosystem, cost, and collaborators favor R. This holds in academic biostatistics, investigator-initiated trials, cohort epidemiology, and most young biotechnology companies. Industry positions will expect SAS with R as a second skill, and academic positions the reverse. A graduate who reads both is eligible for all of them.

29.1.1 Getting access

SAS OnDemand for Academics (ODA), at https://welcome.oda.sas.com/, is the free route. It runs SAS Studio in a browser for students and independent learners. It needs no installation, and it is enough for every SAS block in this chapter. Register, note the user ID it assigns (your home folder is /home/<user-id>/), and upload data through the file pane.1

1 As of 2026-10. ODA sessions have memory and storage limits (about 5 GB each when last checked) and time out after a period of inactivity, so save programs often. SAS University Edition was discontinued in 2021. Altair SLC (formerly WPS) is a paid third-party implementation that runs most SAS code.

Question. A classmate says R is useless for an FDA submission because the FDA requires SAS. What is right and wrong in that?

Answer. The classmate is wrong about the requirement. The FDA requires the datasets as XPT version 5 transport files in CDISC structure. It does not require SAS software, and R writes XPT (haven::write_xpt(), xportr). The classmate is right about the market. Most sponsors and CROs run validated SAS pipelines, so most industry teams expect you to read and write SAS. The screening filter reflects that.

29.2 SAS basics for R users

29.2.1 The DATA step and the PROC step

SAS has two constructs, the DATA step and the PROC step. An R programmer who understands the difference between them has learned most of what makes the language feel foreign. The difference is in the unit of computation. R is vectorized: you write an expression over a whole column. A DATA step reads one observation, runs every statement against it, writes it out, and loops back for the next. The loop is implicit, which is why the code looks vectorized when it is not. Variables persist across statements within a row but reset between rows. A subsetting if discards the observation rather than returning a filtered copy. retain and lag exist because the row-at-a-time model gives no other way to see a neighboring observation. A PROC step works the other way. It consumes a whole dataset and produces listings, tables, or statistical output. An idiomatic program alternates: a DATA step to shape the data, then a PROC to analyze it.

A DATA step:

data work.adults;
  set work.demo;
  if age >= 18;
  age_group = ifn(age < 65, 1, 2);
  log_bmi   = log(bmi);
run;

In R:

library(dplyr)

demo <- tibble(
  usubjid = sprintf("01-%03d", 1:5),
  age     = c(17, 42, 64, 71, 55),
  sex     = c(1L, 2L, 2L, 1L, 2L),
  bmi     = c(21.4, 27.8, 31.2, 24.9, 29.1)
)

adults <- demo |>
  filter(age >= 18) |>
  mutate(age_group = if_else(age < 65, 1L, 2L),
         log_bmi   = log(bmi))

adults
#> # A tibble: 4 × 6
#>   usubjid   age   sex   bmi age_group log_bmi
#>   <chr>   <dbl> <int> <dbl>     <int>   <dbl>
#> 1 01-002     42     2  27.8         1    3.33
#> 2 01-003     64     2  31.2         1    3.44
#> 3 01-004     71     1  24.9         2    3.21
#> 4 01-005     55     2  29.1         1    3.37

And PROC steps on the result. Each procedure has its own syntax. Most share an OUT = option to capture results as a dataset. Most also use some combination of BY, CLASS, and MODEL statements to say which variables partition the data and which enter the analysis.

proc means data = work.adults n mean std median q1 q3 maxdec = 2;
  class age_group;
  var log_bmi;
run;

proc freq data = work.adults;
  tables age_group * sex / chisq;
run;

29.2.2 Libraries and formats

A library (libname) is a directory of SAS datasets. Datasets in WORK, the temporary library, vanish at the end of the session; named libraries persist.

libname mylib '/home/u99999999/data';
data mylib.demo_archive;
  set work.demo;
run;

A format controls how a value displays (1 as 'Male'). An informat controls how input is read. PROC FORMAT defines them. The R analog is a factor with explicit labels:

proc format;
  value sexfmt 1 = 'Male' 2 = 'Female';
run;

data work.demo2;
  set work.demo;
  format sex sexfmt.;
run;

Six procedures cover most data-cleaning code you will read: PROC SORT (arrange()), PROC PRINT (head()), PROC CONTENTS (str(), glimpse()), PROC FREQ (count(), table()), PROC MEANS (summary(), summarize()), and PROC UNIVARIATE (quantile() and distribution summaries).

WarningPitfall

In SAS, a missing number is smaller than every number. The subsetting if age < 18; keeps subjects whose age is missing, because SAS compares a missing value as lower than any value. In R, filter(age < 18) drops them, because the comparison is NA. The same condition therefore selects different subjects in the two languages, with no message in either. Test for missing values explicitly on both sides (if not missing(age) and age < 18;).

Question. In a DATA step, total = total + dose; leaves total missing on every row. Why, and what is the R analog of the fix?

Answer. A DATA step resets non-retained variables to missing at the start of each row. total is therefore missing when the statement runs, and missing plus a number is missing. retain total 0; keeps the running value across rows, as does the sum statement total + dose;, which retains implicitly. In R the whole computation is one vectorized call, cumsum(dose), usually within group_by().

29.3 Procedures and the defaults that differ

29.3.1 Procedure correspondence

The R-to-SAS map for the procedures a clinical biostatistician uses most is in Table 29.1.

Table 29.1: R functions and their SAS procedures. In the survival rows, e is an event indicator and c a censoring indicator.
R SAS
head(df) PROC PRINT DATA = df (OBS = 10);
str(df) PROC CONTENTS DATA = df;
summary(df$x) PROC MEANS DATA = df N MEAN STD;
table(df$x, df$y) PROC FREQ DATA = df; TABLES x*y;
t.test(y ~ g, data = df) PROC TTEST DATA = df; CLASS g; VAR y;
lm(y ~ x1 + x2, data = df) PROC REG DATA = df; MODEL y = x1 x2;
aov(y ~ g, data = df) PROC GLM DATA = df; CLASS g; MODEL y = g;
glm(y ~ x, family = binomial) PROC LOGISTIC DATA = df; MODEL y (EVENT = '1') = x;
glm(y ~ x, family = poisson) PROC GENMOD DATA = df; MODEL y = x / DIST = POISSON LINK = LOG;
lme4::lmer(y ~ x + (1 \| id)) PROC MIXED DATA = df; CLASS id; MODEL y = x; RANDOM INTERCEPT / SUBJECT = id;
mmrm::mmrm(y ~ x * v + us(v \| id)) PROC MIXED; CLASS id v; MODEL y = x v x*v; REPEATED v / SUBJECT = id TYPE = UN;
survfit(Surv(t, e) ~ g) PROC LIFETEST DATA = df; TIME t*c(1); STRATA g;
coxph(Surv(t, e) ~ x) PROC PHREG DATA = df; MODEL t*c(1) = x;

29.3.2 PROC GLM and estimated marginal means

proc glm data = work.penguins;
  class species;
  model body_mass_g = species flipper_length_mm;
  lsmeans species / pdiff cl;
run;
quit;

R equivalent:

library(palmerpenguins)
penguins_clean <- na.omit(penguins)

fit <- lm(body_mass_g ~ species + flipper_length_mm,
          data = penguins_clean)
emmeans::emmeans(fit, "species", contr = "pairwise",
                 infer = TRUE)
#> $emmeans
#>  species   emmean   SE  df lower.CL upper.CL t.ratio p.value
#>  Adelie      4147 45.5 329     4058     4237  91.073 <0.0001
#>  Chinstrap   3942 48.0 329     3848     4036  82.195 <0.0001
#>  Gentoo      4432 60.7 329     4312     4551  73.048 <0.0001
#> 
#> Confidence level used: 0.95 
#> 
#> $contrasts
#>  contrast           estimate   SE  df lower.CL upper.CL t.ratio p.value
#>  Adelie - Chinstrap      205 57.6 329     69.8    340.9   3.568  0.0012
#>  Adelie - Gentoo        -285 95.4 329   -509.2    -59.8  -2.981  0.0086
#>  Chinstrap - Gentoo     -490 87.0 329   -694.7   -285.1  -5.631 <0.0001
#> 
#> Confidence level used: 0.95 
#> Conf-level adjustment: tukey method for comparing a family of 3 estimates 
#> P value adjustment: tukey method for comparing a family of 3 estimates

The lsmeans statement produces estimated marginal means (least-squares means). The emmeans package is the R counterpart. Marginal means do not depend on which level is the reference, which makes them the right quantities to compare across the two languages. The coefficients do depend on it. PROC GLM uses a less-than-full-rank parameterization whose solution reports each species level against the last sorted level (Gentoo). By contrast, lm() reports each against the first (Adelie). The flipper_length_mm slope, the overall fit, and the fitted values match exactly. To make the species rows match term for term, relevel in R with relevel(species, ref = 'Gentoo').

29.3.3 PROC LOGISTIC and reference coding

proc logistic data = work.trial;
  class treatment (param = ref ref = 'placebo')
        sex (param = ref ref = 'M');
  model outcome (event = '1') = treatment age sex;
  oddsratio treatment;
run;

R equivalent:

set.seed(4)
n <- 200
trial <- data.frame(
  treatment = rep(c("placebo", "active"), each = n / 2),
  age       = round(rnorm(n, 62, 9)),
  sex       = sample(c("M", "F"), n, replace = TRUE),
  outcome   = rbinom(n, 1, 0.3)
)

trial$treatment <- relevel(factor(trial$treatment),
                           ref = "placebo")
trial$sex <- relevel(factor(trial$sex), ref = "M")
fit <- glm(outcome ~ treatment + age + sex,
           family = binomial, data = trial)
broom::tidy(fit, exponentiate = TRUE, conf.int = TRUE)
#> # A tibble: 4 × 7
#>   term            estimate std.error statistic p.value conf.low conf.high
#>   <chr>              <dbl>     <dbl>     <dbl>   <dbl>    <dbl>     <dbl>
#> 1 (Intercept)        0.136    1.21      -1.64    0.101   0.0120      1.43
#> 2 treatmentactive    0.827    0.320     -0.592   0.554   0.439       1.55
#> 3 age                1.02     0.0185     0.945   0.344   0.982       1.06
#> 4 sexF               1.11     0.322      0.334   0.738   0.591       2.10

Three settings in the SAS code exist only to match R. First, param = ref requests reference coding, which is R’s default. Without it, PROC LOGISTIC uses effect coding (sum-to-zero), whose coefficients are deviations from the average over levels. Second, ref = names the reference level. SAS otherwise takes the last level in sort order and R the first. For active and placebo, the defaults therefore pick opposite references and report the same effect with opposite signs. Third, event = '1' makes SAS model the probability that outcome is 1. By default PROC LOGISTIC models the lowest ordered value, here 0, which flips the sign of every coefficient. PROC GENMOD defaults instead to the less-than-full-rank PARAM = GLM coding. That coding behaves like reference coding with the last level as reference. PROC GLM and PROC MIXED use their own less-than-full-rank coding and do not take param =.

29.3.4 The defaults that differ

Table 29.2 collects the defaults that make an R fit and a SAS fit of ‘the same model’ disagree. Each is silent. Both programs run and print a plausible table.

Table 29.2: Defaults that differ between R and SAS. Set every row explicitly in both programs before comparing numbers.
Setting R default SAS default Set both sides to
Reference level of a categorical predictor First level (alphabetical unless set) Last level in sort order relevel(x, ref =); CLASS x (REF = '...')
Coding of a categorical predictor Reference (treatment) contrasts LOGISTIC: effect coding; GENMOD: PARAM = GLM; GLM, MIXED: less-than-full-rank PARAM = REF, or compare marginal means
Modeled outcome in logistic regression P(y = 1) (the second factor level) The lowest ordered value, P(y = 0) MODEL y (EVENT = '1') =
Mixed-model covariance lmer(): random effects only; mmrm(): the structure in the formula RANDOM: variance components (VC); REPEATED needs TYPE = TYPE = UN with us(), or the same named structure
Denominator degrees of freedom lmer(): none; mmrm(): Satterthwaite Containment or between-within, by statement method = "Kenward-Roger"; DDFM = KR
Tied event times in a Cox model Efron Breslow ties = "breslow", or TIES = EFRON
Confidence interval for a survival curve Log (conf.type = "log") Log-log (CONFTYPE = LOGLOG) Either, stated
Censoring indicator Surv(t, e): e = 1 is an event TIME t*c(list): values in the list are censored CDISC: Surv(AVAL, CNSR == 0); aval*cnsr(1 2)
Missing value in a comparison NA; filter() drops the row Smaller than any number; x < 5 is true Test missing() and is.na() explicitly
Date origin 1970-01-01 1960-01-01 as.Date(x, origin = "1960-01-01") for bare numbers
Sums of squares in ANOVA anova(): sequential (Type I) PROC GLM prints Type I and Type III car::Anova(type = 3) with sum contrasts
ImportantLLM prompt

Use a model to translate between the languages, with the defaults table as the acceptance criteria.

Context. Below is an R analysis I need reproduced in SAS for a CRO validation: [the R code, and the variable names and types of the input dataset; no data rows].

Constraints. Write SAS 9.4 code using PROC LOGISTIC (or the procedure I name). Set the reference level of every CLASS variable with PARAM = REF and REF =, state EVENT = for the modeled outcome, and for any survival model state TIES = and list every censoring code in TIME aval*cnsr(...).

Criteria. For each row of this table paste 29.2, say which line of your code sets it, or why it does not apply. Name the output table (ODS OUTPUT) whose estimates I should compare with broom::tidy() in R.

Failure mode. Models translate the syntax and leave the defaults unchanged. The result has no EVENT =, no REF =, and Breslow ties against R’s Efron. For survival models, the event and censoring codes are often confused. In R’s Surv(), a status of 1 marks an event. SAS’s TIME aval*cnsr(1) lists the values that mark censoring. The CDISC CNSR variable codes 0 as the event. A model that writes aval*cnsr(0) for an ADaM dataset has inverted the analysis. Check. Run both programs on the same data and compare estimates to four decimal places. Trace any disagreement to a row of Table 29.2 before accepting either.

29.3.5 A side-by-side example

A penguin model in both languages:

fit <- lm(body_mass_g ~ flipper_length_mm + species,
          data = na.omit(penguins))
broom::tidy(fit, conf.int = TRUE)
#> # A tibble: 4 × 7
#>   term              estimate std.error statistic  p.value conf.low conf.high
#>   <chr>                <dbl>     <dbl>     <dbl>    <dbl>    <dbl>     <dbl>
#> 1 (Intercept)        -4013.     586.       -6.85 3.74e-11  -5166.    -2860. 
#> 2 flipper_length_mm     40.6      3.08     13.2  3.64e-32     34.5      46.7
#> 3 speciesChinstrap    -205.      57.6      -3.57 4.14e- 4   -319.      -92.1
#> 4 speciesGentoo        285.      95.4       2.98 3.08e- 3     96.8     472.
proc import datafile = '/home/u99999999/penguins.csv'
            out = work.penguins dbms = csv replace;
  getnames = yes;
run;

data work.penguins_clean;
  set work.penguins;
  if cmiss(of _all_) = 0;
run;

proc glm data = work.penguins_clean;
  class species;
  model body_mass_g = flipper_length_mm species / clparm solution;
run;
quit;

The slope, the overall fit, and the fitted values agree. The species rows differ by reference level, as in the PROC GLM example above. One more difference can hide in the import. R’s read.csv() reads the text NA as missing. PROC IMPORT treats it as an ordinary value and may read a numeric column that contains it as character. As a result, cmiss() may count different rows as complete. Compare the number of observations used before comparing estimates.

29.3.6 Exercises

These need no SAS. Predict first, then check the prediction in R.

  1. A SAS programmer fits proc logistic data = adsl; class trt01p sex; model event30 = trt01p age sex; run; on the HF-HOME ADSL joined to the 30-day outcome, with no options. You fit glm(event30 ~ TRT01P + AGE + SEX, binomial) with R’s defaults. Predict, for the AGE coefficient and the treatment coefficient, how the two will differ. Then reproduce the SAS defaults in R to confirm.

Three defaults differ. First, SAS models P(event30 = 0), the lowest ordered value, so every coefficient changes sign. Second, SAS uses effect coding. A two-level CLASS variable gets one column coded +1 and -1, and its coefficient is half the difference between the levels. Third, SAS sorts trt01p levels alphabetically ('Home health' before 'Usual care'), as R does, but codes the first level +1. The prediction is as follows. SAS’s AGE coefficient is the negative of R’s. SAS’s treatment coefficient is half of R’s TRT01PUsual care coefficient, with the same sign. R reproduces SAS’s defaults with contr.sum and the outcome reversed:

source(file.path("..", "..", "R", "hfhome.R"))
hf_dir <- file.path("..", "data", "raw_data", "hfhome")
outcomes <- readr::read_csv(
  file.path(hf_dir, "outcomes.csv"),
  col_types = readr::cols(patient_id = "c", .default = "?"))

lr_data <- hfhome_sdtm()$dm |>
  transmute(USUBJID, TRT01P = ARM, AGE, SEX) |>
  inner_join(transmute(outcomes,
                       USUBJID = paste("HFHOME", patient_id,
                                       sep = "-"),
                       event30 = event_30d),
             by = "USUBJID", relationship = "one-to-one") |>
  filter(!is.na(event30)) |>
  mutate(TRT01P = factor(TRT01P), SEX = factor(SEX))

r_fit <- glm(event30 ~ TRT01P + AGE + SEX, family = binomial,
             data = lr_data)
sas_like <- glm(I(1 - event30) ~ TRT01P + AGE + SEX,
                family = binomial, data = lr_data,
                contrasts = list(TRT01P = "contr.sum",
                                 SEX = "contr.sum"))

rbind(r = coef(r_fit), sas_defaults = coef(sas_like))
#>              (Intercept) TRT01PUsual care         AGE       SEXM
#> r              -3.066234       0.14758053  0.02280302 0.17502248
#> sas_defaults    2.904932       0.07379026 -0.02280302 0.08751124
stopifnot(
  isTRUE(all.equal(coef(sas_like)[["AGE"]], -coef(r_fit)[["AGE"]])),
  isTRUE(all.equal(coef(sas_like)[["TRT01P1"]],
                   coef(r_fit)[["TRT01PUsual care"]] / 2))
)

This reproduces what SAS’s defaults imply, by construction. It is not a SAS run. SAS’s log would say which outcome it modeled (‘Probability modeled is event30=0.’). That is the line to look for when two answers have opposite signs.

  1. Fit the Cox model of HF-HOME’s ADTTE (time to readmission or death by randomized arm) in R twice, once with R’s default handling of tied event times and once with SAS’s. Predict whether the hazard ratios differ in the second decimal place.

The prediction is as follows. Times are recorded in whole days, so many events are tied. Breslow’s approximation pulls the coefficient toward zero relative to Efron’s. With about a fifth of subjects having an event, the approximation error is small. We expect agreement to two decimal places and a difference in the third or fourth.

efron   <- coxph(Surv(AVAL, CNSR == 0) ~ TRT01P, data = adtte)
breslow <- coxph(Surv(AVAL, CNSR == 0) ~ TRT01P, data = adtte,
                 ties = "breslow")
round(c(efron = exp(coef(efron)), breslow = exp(coef(breslow))), 4)
#>   efron.TRT01PHome health breslow.TRT01PHome health 
#>                    0.8517                    0.8525

The two hazard ratios differ by 0.0007. That is too little to change any conclusion, but enough to fail a validation that compares results to four decimal places. PROC PHREG without TIES = EFRON reproduces the second number, not the first. Neither is wrong. The specification should name one, and both programs should use it.

Question. You translate a logistic regression from R to SAS, set param = ref, and the treatment coefficient now has the same magnitude as R’s but the opposite sign. Name the two settings that could each explain it.

Answer. The first is the reference level. SAS takes the last level and R the first, so ref = must name the same level on both sides. The second is the modeled outcome. SAS models the lowest ordered value unless event = '1'. Either alone flips the sign, and both together flip it back. That is why a sign that agrees is not evidence that the settings do.

29.4 Mixed models and MMRM in both languages

29.4.1 A random intercept

proc mixed data = work.long covtest;
  class subject visit treatment;
  model y = treatment visit treatment*visit / solution;
  random intercept / subject = subject;
run;

R equivalent:

library(lme4)

set.seed(5)
subject_effect <- rnorm(40, 0, 1.5)

# treatment is assigned per subject, so it is constant within
# subject, as in a parallel-group trial
long <- expand.grid(subject = factor(1:40), visit = factor(1:3)) |>
  mutate(
    treatment = if_else(as.integer(subject) <= 20,
                        "placebo", "active"),
    treatment = relevel(factor(treatment), ref = "placebo"),
    y = 10 + 2 * (treatment == "active") +
        0.5 * as.integer(visit) +
        subject_effect[as.integer(subject)] +
        rnorm(n(), 0, 2)
  )

stopifnot(all(tapply(long$treatment, long$subject,
                     \(x) length(unique(x))) == 1))

fit <- lmer(y ~ treatment * visit + (1 | subject), data = long)
summary(fit)$coefficients
#>                          Estimate Std. Error    t value
#> (Intercept)            10.3179110  0.5784227 17.8380125
#> treatmentactive         2.3571550  0.8180132  2.8815611
#> visit2                  0.5167972  0.5741178  0.9001588
#> visit3                  0.5467634  0.5741178  0.9523541
#> treatmentactive:visit2  0.5133472  0.8119251  0.6322593
#> treatmentactive:visit3  1.1889715  0.8119251  1.4643856

Both fit the same model. visit is categorical on both sides (CLASS in SAS, a factor in R), and both estimate by REML (restricted maximum likelihood). The fixed-effect tables still differ term for term. PROC MIXED zeroes the last level of each CLASS variable (visit 3, and placebo, which sorts after active), while R zeroes the first. Placebo is the reference on both sides. For visit, compare fitted means (LSMEANS in SAS, emmeans in R) rather than coefficients. PROC MIXED’s default covariance for a RANDOM statement is variance components (VC). For a random intercept, that matches lme4’s default. A random slope with an unstructured covariance needs random intercept visit / subject = subject type = un;.

29.4.2 MMRM: a mixed model for repeated measures

The primary analysis of a continuous endpoint measured at scheduled visits in a trial is usually an MMRM. Visit, treatment, and their interaction enter as fixed effects. There are no random effects at all. Instead, an unstructured covariance links a subject’s visits, so that each visit has its own variance and each pair its own correlation. In SAS this is PROC MIXED with a REPEATED statement. In R it is the mmrm package (Sabanes Bove et al., 2026), written by an industry working group to reproduce SAS’s results.

proc mixed data = work.long method = reml;
  class subject visit treatment;
  model y = treatment visit treatment*visit / ddfm = kr solution;
  repeated visit / subject = subject type = un;
  lsmeans treatment*visit / diff cl;
run;

R equivalent:

library(mmrm)

fit_mmrm <- mmrm(y ~ treatment * visit + us(visit | subject),
                 data = long, method = "Kenward-Roger")
emmeans::emmeans(fit_mmrm, ~ treatment | visit) |>
  pairs(reverse = TRUE)
#> visit = 1:
#>  contrast         estimate    SE df t.ratio p.value
#>  active - placebo     2.36 0.660 38   3.571  0.0010
#> 
#> visit = 2:
#>  contrast         estimate    SE df t.ratio p.value
#>  active - placebo     2.87 0.841 38   3.414  0.0015
#> 
#> visit = 3:
#>  contrast         estimate    SE df t.ratio p.value
#>  active - placebo     3.55 0.884 38   4.013  0.0003

The two sides agree on the fitted model only because three settings were made to agree. These are the covariance (TYPE = UN and us()), the estimation method (REML in both), and the denominator degrees of freedom (DDFM = KR and method = "Kenward-Roger"). If you leave out DDFM = KR, SAS uses the between-within method. With TYPE = UN and no RANDOM statement, that method gives every effect the between-subject degrees of freedom. If you leave out method =, mmrm uses Satterthwaite’s. The estimates agree either way. The confidence intervals and p-values do not.

TipVerification

Without SAS, check the MMRM against an independent R implementation of the same model: generalized least squares with an unstructured correlation and a separate variance per visit.

fit_gls <- nlme::gls(
  y ~ treatment * visit, data = long, method = "REML",
  correlation = nlme::corSymm(form = ~ as.integer(visit) | subject),
  weights = nlme::varIdent(form = ~ 1 | visit)
)
stopifnot(isTRUE(all.equal(coef(fit_mmrm), coef(fit_gls),
                           tolerance = 1e-4)))
cbind(mmrm = coef(fit_mmrm), gls = coef(fit_gls))
#>                              mmrm        gls
#> (Intercept)            10.3179110 10.3179110
#> treatmentactive         2.3571550  2.3571550
#> visit2                  0.5167972  0.5167972
#> visit3                  0.5467634  0.5467634
#> treatmentactive:visit2  0.5133472  0.5133472
#> treatmentactive:visit3  1.1889715  1.1889715

Agreement between two R packages is evidence that mmrm fit the model you specified. Agreement with SAS still has to be checked on SAS output, against the same three settings.

Question. Your R MMRM and a colleague’s PROC MIXED give the same treatment difference at the last visit but different confidence intervals. The SAS code has repeated visit / subject = subject type = un; and no DDFM =. What do you change?

Answer. The degrees of freedom. Without DDFM =, a model with only a REPEATED statement uses the between-within method. Your mmrm fit used Kenward-Roger or Satterthwaite. Add DDFM = KR in SAS (or choose the same method in mmrm), and the intervals should then agree. Equal estimates with unequal intervals point at the degrees of freedom or the covariance structure, not the mean model.

29.5 Survival analysis on the HF-HOME ADTTE

This section reuses the HF-HOME ADSL and ADTTE built in Section 28.4. The chunk that rebuilds them here is hidden. It repeats the derivation of that section, so that this chapter renders on its own.

The SAS side reads adtte.xpt, written from R in Section 29.7. CNSR takes the values 1 (no event by day 30) and 2 (lost to follow-up), so the censoring list names both:

proc lifetest data = work.adtte plots = survival(atrisk);
  where ittfl = 'Y';
  time aval * cnsr(1 2);
  strata trt01p;
run;

proc phreg data = work.adtte;
  where ittfl = 'Y';
  class trt01p (param = ref ref = 'Usual care')
        sex    (param = ref ref = 'F');
  model aval * cnsr(1 2) = trt01p age sex / ties = efron risklimits;
run;

R equivalent:

analysis <- filter(adtte, ITTFL == "Y")

fit_km <- survfit(Surv(AVAL, CNSR == 0) ~ TRT01P, data = analysis)
fit_cox <- coxph(Surv(AVAL, CNSR == 0) ~ TRT01P + AGE + SEX,
                 data = analysis)
fit_cox
#> Call:
#> coxph(formula = Surv(AVAL, CNSR == 0) ~ TRT01P + AGE + SEX, data = analysis)
#> 
#>                        coef exp(coef)  se(coef)      z        p
#> TRT01PHome health -0.165974  0.847068  0.088947 -1.866   0.0620
#> AGE                0.019674  1.019869  0.004161  4.728 2.27e-06
#> SEXM               0.156244  1.169112  0.090363  1.729   0.0838
#> 
#> Likelihood ratio test=28.17  on 3 df, p=3.338e-06
#> n= 2432, number of events= 508
stopifnot(fit_cox$n == nrow(analysis))

Each line of the SAS code answers a row of Table 29.2. cnsr(1 2) lists every censoring value, the counterpart of R’s CNSR == 0. ties = efron matches coxph(). ref = 'Usual care' matches the factor level order set in ADSL. Finally, sex appears in the CLASS statement because PROC PHREG stops with an error on a character variable in MODEL that is not declared there. Its reference, 'F', is the level R chooses by default (first alphabetically).

WarningPitfall

time aval*cnsr(1) on a dataset with CNSR = 2 counts the lost-to-follow-up subjects as events. SAS treats every value not in the list as an event, so the 163 HF-HOME subjects lost to follow-up would become early events, at their last contact, with no message. List every censoring code the dataset contains, and check the event count in the PROC LIFETEST summary against sum(CNSR == 0).

Question. The PROC PHREG output reports 671 events; R’s coxph() reports 508 on the same file. Which line of the SAS code do you check first?

Answer. The MODEL statement’s censoring list. 671 is 508 plus the 163 subjects lost to follow-up. That is what aval*cnsr(1) produces when CNSR also takes the value 2. A difference in the event count is always a data or coding difference, never a default of the estimator. Check it before comparing any estimate.

29.6 Reading SAS logs

SAS writes three tiers of message to the log:

  • ERROR: the step stopped. Fix and rerun.
  • WARNING: something unexpected happened and the program continued. Always inspect.
  • NOTE: information about what the program did. Most are benign; a few report lost or multiplied data, and SAS does not flag them.

29.6.1 An annotated log

The log below is from a DATA step that merges a demographics file with a visits file (display-only; constructed for this chapter, not produced by a SAS run). The annotations mark what to read.

1    data work.analytic;
2      merge work.demo work.visits;
3      by patient_id;
4      pulse_pressure = sbp - dbp;
5      sbp_high = (sbp > 140);
6    run;

WARNING: Multiple lengths were specified for the BY variable   (1)
         patient_id by input data sets. This might cause
         unexpected results.
NOTE: MERGE statement has more than one data set with repeats  (2)
      of BY values.
NOTE: Missing values were generated as a result of performing  (3)
      an operation on missing values.
      Each place is given by: (Number of times) at
      (Line):(Column).
      41 at 4:24
NOTE: There were 2432 observations read from the data set
      WORK.DEMO.
NOTE: There were 6317 observations read from the data set
      WORK.VISITS.
NOTE: The data set WORK.ANALYTIC has 6330 observations and 12  (4)
      variables.
  1. The BY variable has different lengths in the two inputs, for example $4 in one and $8 in the other. Values can be truncated or fail to match, so some subjects may not merge. Make the lengths equal before the merge.
  2. Both datasets have more than one row for some patient_id. Within such a group, MERGE pairs rows one to one in order and repeats the last row of the shorter dataset. It does not form every combination as an SQL join would. The result is wrong, and the step ‘completes’. A demographics file should have one row per patient, so this NOTE means it does not.
  3. The subtraction on line 4 met a missing sbp or dbp 41 times. Line 5 compared the same missing values with 140 and produced no message at all. A missing value is smaller than any number, so sbp_high is 0, not missing, and those visits are counted as not high. The NOTE on line 4 is the only sign of the silent comparison on line 5.
  4. More rows than either input. Without IN= flags, MERGE is a full outer join that keeps unmatched rows from both datasets. The count can therefore rise from unmatched keys as well as from repeats. 6,330 against 6,317 visits means 13 rows to account for.

Read the log end to end after every run, not only the last lines. For automated checking, PROC SQL can assert a row count and write an ERROR line that log scanners catch:

proc sql noprint;
  select count(*) into :n_visits from work.visits;
  select count(*) into :n_merged from work.analytic;
quit;
%if &n_visits ne &n_merged %then %do;
  %put ERROR: Merge changed the row count: &n_visits -> &n_merged;
%end;
ImportantLLM prompt

Context. Below is the complete log of a SAS program that merges and derives an analysis dataset, with patient identifiers replaced by synthetic values: [log]. The program should produce one row per visit from a demographics file with one row per patient.

Constraints. Do not rewrite the program yet.

Criteria. List every ERROR, every WARNING, and every NOTE that could indicate lost, multiplied, truncated, or silently missing data, quoting the line. For each, say what in the data would produce it and what check would confirm it.

Failure mode. Models explain the ERRORs well and pass over the NOTEs, which is where the merge and missing-value problems are. They also suggest suppressing a WARNING rather than finding its cause. Check. Confirm each flagged message against the data (a count() of duplicated keys, a comparison of variable lengths with PROC CONTENTS). Fix the cause, rerun, and require a log with no WARNING and no merge or missing-value NOTE. Logs can contain data values, so replace identifiers before sending one (Section 12.3).

29.6.2 Exercises

  1. Read this log (display-only; constructed for the exercise) and say what happened, how many records it affected, and what you would change.

    NOTE: Character values have been converted to numeric values
          at the places given by: (Line):(Column).
          14:12
    NOTE: Invalid numeric data, sbp_discharge='NA' , at line 14
          column 12.
    NOTE: Missing values were generated as a result of performing
          an operation on missing values.
          Each place is given by: (Number of times) at
          (Line):(Column).
          78 at 15:20
    NOTE: There were 2432 observations read from the data set
          WORK.CRF.
    NOTE: The data set WORK.CRF2 has 2432 observations and 9
          variables.

sbp_discharge arrived as character, and line 14 used it in a numeric expression, so SAS converted it implicitly. The text 'NA' (and any other non-numeric code) became missing, with an ‘Invalid numeric data’ note for each such value. SAS prints only the first several of these notes, so the log does not say how many there were. Line 15 then produced missing results 78 times, which is the affected count for that expression. The row count is unchanged, which is why the step looks fine.

The fix is to convert deliberately. Read the column as character, and recode the site’s missing-value codes ('NA', '-99', empty) to missing explicitly. Then convert with input(sbp_discharge, best.) and count the missing values before and after. HF-HOME’s crf_export.csv uses exactly these codes; Chapter 21 gives the R side.

  1. A colleague’s log ends with NOTE: The data set WORK.ADSL has 2432 observations and 40 variables. and contains no ERROR or WARNING. They conclude the merge that built it was correct. Name two problems this log cannot rule out, and the check for each.

A count equal to the number of subjects rules out neither of the failures Chapter 18 describes. First, some subjects may have failed to match. A full outer MERGE without IN= keeps them, with missing values in the other dataset’s variables. Second, a repeated key may have been paired row by row and replaced a correct value with a wrong one, which leaves the count unchanged. For the first, count missing values in a variable that comes from each input (PROC MEANS NMISS or PROC FREQ). For the second, confirm one row per key in each input before the merge (PROC SORT NODUPKEY into a separate dataset and compare counts, or PROC SQL with GROUP BY ... HAVING COUNT(*) > 1). The absence of a WARNING is not evidence, because the repeats NOTE is a NOTE.

Question. Why does the book treat NOTE: MERGE statement has more than one data set with repeats of BY values as more dangerous than most ERRORs?

Answer. An ERROR stops the step, so nothing downstream runs on its output. The repeats NOTE lets the step finish and produce a dataset with the expected columns and a plausible row count, built from mismatched rows. It is the SAS form of the many-to-many join of Chapter 18, without the warning dplyr gives.

29.7 Moving data between SAS and R

A mixed-language project tends to go wrong at the boundary between the languages. Figure 29.2 marks it, with the properties to check every time something crosses.

flowchart LR
  R1["<b>R</b><br/><i>clean, derive</i>"]
  R1 -->|"haven::write_xpt<br/>version = 5"| X1[".xpt"]
  X1 -->|"libname xport<br/>proc copy"| S["<b>SAS</b><br/><i>analyze, ODS output</i>"]
  S -->|"libname out xport"| X2[".xpt"]
  X2 -->|"haven::read_xpt"| R2["<b>R</b><br/><i>tabulate, plot</i>"]
  C["<b>Check at every crossing</b><br/><i>row count, variable names,<br/>types and labels</i>"] -.-> X1
  C -.-> X2
Figure 29.2: The R and SAS boundary. Transport version 5 is the durable interchange format and the one the FDA requires. Each crossing is a place where variable names can be truncated, types can change, and labels can be lost, so each crossing deserves an explicit check rather than an assumption.

29.7.1 R to SAS

XPT version 5 allows variable names of at most eight characters and has no factor type. haven::write_xpt() handles both without an error, in ways you need to know. It truncates a longer name to eight characters, so two names that share their first eight collide. It also writes a factor as its integer codes, so TRT01P arrives in SAS as 1 and 2. Convert factors to character and check name lengths before writing:

library(haven)

xpt_dir <- file.path(tempdir(), "xpt")
dir.create(xpt_dir, showWarnings = FALSE)

adtte_out <- adtte |>
  mutate(TRT01P = as.character(TRT01P))
attr(adtte_out$AVAL, "label") <- "Analysis Value (days)"
attr(adtte_out$CNSR, "label") <- "Censor (0 = event)"

stopifnot(all(nchar(names(adtte_out)) <= 8),
          !any(vapply(adtte_out, is.factor, logical(1))))
write_xpt(adtte_out, file.path(xpt_dir, "adtte.xpt"),
          version = 5, name = "ADTTE")

In SAS:

libname x xport '/home/u99999999/adtte.xpt';
proc copy in = x out = work; run;
libname x clear;

29.7.2 SAS to R, and the round trip

haven::read_xpt() and haven::read_sas() (for .sas7bdat) bring SAS data back. They keep each variable’s label as an attribute and convert variables that carry a SAS date format to Date. SAS stores a date as days since 1 January 1960, and R counts from 1 January 1970. A date that arrives as a bare number, without a format, is therefore ten years wrong unless converted with as.Date(x, origin = "1960-01-01").

TipVerification

Read the transport file back and compare it with what was written: row count, names, types, labels, dates, and values.

back <- read_xpt(file.path(xpt_dir, "adtte.xpt"))

stopifnot(
  nrow(back) == nrow(adtte_out),
  identical(names(back), names(adtte_out)),
  inherits(back$ADT, "Date"),
  identical(attr(back$AVAL, "label"), "Analysis Value (days)"),
  isTRUE(all.equal(as.data.frame(zap_labels(back)),
                   as.data.frame(zap_labels(adtte_out)),
                   check.attributes = FALSE))
)
str(back[c("USUBJID", "TRT01P", "ADT", "AVAL", "CNSR")])
#> tibble [2,432 × 5] (S3: tbl_df/tbl/data.frame)
#>  $ USUBJID: chr [1:2432] "HFHOME-0001" "HFHOME-0002" "HFHOME-0003" "HFHOME-0004" ...
#>  $ TRT01P : chr [1:2432] "Home health" "Home health" "Usual care" "Usual care" ...
#>  $ ADT    : Date[1:2432], format: "2024-03-02" "2024-03-02" ...
#>  $ AVAL   : num [1:2432] 30 30 30 30 30 30 30 30 30 18 ...
#>   ..- attr(*, "label")= chr "Analysis Value (days)"
#>  $ CNSR   : num [1:2432] 1 1 1 1 1 1 1 1 1 0 ...
#>   ..- attr(*, "label")= chr "Censor (0 = event)"

CNSR comes back as a double, because XPT stores every number as one. all.equal() compares values, so that change passes, and it is harmless. TRT01P comes back as character with its levels in no particular order. Set the reference level again before fitting anything (Table 29.2).

For workflows in which R prepares the data, SAS fits the models, and R produces the tables, SAS writes its results to a second transport file through ODS (display-only):

proc phreg data = work.adtte;
  where ittfl = 'Y';
  class trt01p (param = ref ref = 'Usual care');
  model aval * cnsr(1 2) = trt01p / ties = efron risklimits;
  ods output ParameterEstimates = pe;
run;

libname out xport '/home/u99999999/results.xpt';
data out.pe;
  set pe(keep = Parameter Estimate StdErr HazardRatio
         rename = (HazardRatio = HR));
run;
libname out clear;

HazardRatio is renamed because version 5 names are limited to eight characters. The R side reads the file and builds the table. Below, a file written from R’s own fit stands in for the one SAS would write, so that the R side runs here.

cox_itt <- coxph(Surv(AVAL, CNSR == 0) ~ TRT01P, data = analysis)
results_path <- file.path(xpt_dir, "results.xpt")
write_xpt(
  data.frame(Parameter = "TRT01P",
             Estimate  = unname(coef(cox_itt)),
             StdErr    = unname(sqrt(diag(vcov(cox_itt)))),
             HR        = unname(exp(coef(cox_itt)))),
  results_path, version = 5)

results <- read_xpt(results_path)
gt::gt(results) |>
  gt::fmt_number(columns = c(Estimate, StdErr, HR), decimals = 3)
Paramete Estimate StdErr HR
TRT01P −0.160 0.089 0.852

29.7.3 Exercises

  1. Write the HF-HOME ADSL to a transport file without converting TRT01P, read it back, and show what happened to the treatment variable. Then fix the export so that the round trip preserves it.
adsl_path <- file.path(xpt_dir, "adsl.xpt")

write_xpt(adsl, adsl_path, version = 5)
table(read_xpt(adsl_path)$TRT01P)
#> 
#>    1    2 
#> 1216 1216

write_xpt(mutate(adsl, TRT01P = as.character(TRT01P)), adsl_path,
          version = 5)
fixed <- read_xpt(adsl_path)
table(fixed$TRT01P)
#> 
#> Home health  Usual care 
#>        1216        1216
stopifnot(identical(sort(unique(fixed$TRT01P)), sort(arms)))

The first export writes the factor’s integer codes. The arms therefore arrive as 1 and 2, with nothing to say which is which. A SAS program that sets ref = 'Usual care' then fails to find the level. One that does not set it silently uses 2 as the reference. Converting to character writes the labels. In R, re-create the factor with explicit levels after reading.

Question. A SAS dataset arrives in R with a column RANDDT whose values are around 23,400 and no format. What are the dates, roughly, and how do you convert them?

Answer. Days since 1 January 1960, so about 64 years after 1960, in 2024. as.Date(RANDDT, origin = "1960-01-01") converts them. Converting with R’s default origin would place them in 2034, ten years late. Every derived duration would still be right, which is why the error survives until someone reads a date.

29.8 Rules of thumb

  1. Habit 8: a bug that produces a plausible number is the expensive kind. Two languages that disagree by default both print a table; set every row of Table 29.2 explicitly before comparing.
  2. Habit 9: test the statistics, not the shape. Equivalence means estimates that agree to several decimal places on the same data, and a disagreement is a default to find, not noise.
  3. Habit 6: count before and after every join. Read the whole SAS log after every run; the MERGE repeats NOTE is a many-to-many join that did not warn you.

29.9 Cumulative practice

  1. Cumulative (uses Chapter 28). Write the HF-HOME ADTTE to a transport file, read it back, and refit the ITT Cox model on the file you read. Set every relevant row of Table 29.2 so that your R fit reproduces what the PROC PHREG program in Section 29.5 would compute, and write the SAS program that would confirm it.
  2. On your own work (no key). If you have SAS access (ODA is enough), run that PROC PHREG program on your adtte.xpt and compare the hazard ratios with R’s to four decimal places. Before you look, predict from Table 29.2 which numbers will differ if you remove ties = efron.
reread <- read_xpt(file.path(xpt_dir, "adtte.xpt")) |>
  mutate(TRT01P = factor(TRT01P, levels = arms),
         SEX    = factor(SEX, levels = c("F", "M"))) |>
  filter(ITTFL == "Y")

refit <- coxph(Surv(AVAL, CNSR == 0) ~ TRT01P + AGE + SEX,
               data = reread, ties = "efron")
stopifnot(nrow(reread) == nrow(analysis),
          isTRUE(all.equal(coef(refit), coef(fit_cox))))
round(exp(cbind(HR = coef(refit), confint(refit))), 3)
#>                      HR 2.5 % 97.5 %
#> TRT01PHome health 0.847 0.712  1.008
#> AGE               1.020 1.012  1.028
#> SEXM              1.169 0.979  1.396

Four rows matter here. The reference level is re-created as Usual care after the round trip, matching ref = 'Usual care'. SEX has reference F on both sides. The ties method is Efron, stated in both. The censoring codes are CNSR == 0 in R and cnsr(1 2) in SAS. The SAS program is the PROC PHREG block of Section 29.5 with libname x xport and proc copy in front of it. The refit equals the original fit. That is the check that the round trip lost nothing the model uses.

29.10 Cheat sheet

Table 29.3: R to SAS at a glance.
Task R SAS
Read a CSV readr::read_csv("f.csv") PROC IMPORT DATAFILE = 'f.csv' OUT = work.f DBMS = CSV;
Keep rows filter(age >= 18) if age >= 18; (keeps missing age; add not missing(age))
New variable mutate(log_bmi = log(bmi)) log_bmi = log(bmi); in a DATA step
Running total mutate(total = cumsum(dose)) retain total 0; total = total + dose;
Sort arrange(id, visit) PROC SORT DATA = d; BY id visit;
Join by key left_join(x, y, by = "id", relationship = "many-to-one") MERGE x (IN = a) y; BY id; IF a; after checking one row per id in y
Summarize by group group_by(g) \|> summarize(m = mean(x)) PROC MEANS; CLASS g; VAR x; OUTPUT OUT = s MEAN = m;
Labels for codes factor(sex, 1:2, c("Male", "Female")) PROC FORMAT; VALUE sexfmt 1 = 'Male' 2 = 'Female';
Set the reference relevel(trt, ref = "Placebo") CLASS trt (PARAM = REF REF = 'Placebo');
Model P(y = 1) glm(y ~ x, family = binomial) MODEL y (EVENT = '1') = x;
ADaM survival Surv(AVAL, CNSR == 0) TIME aval*cnsr(1 2); (every censoring code)
Cox ties coxph(..., ties = "efron") (default) MODEL ... / TIES = EFRON;
Write transport write_xpt(df, "f.xpt", version = 5) LIBNAME x XPORT 'f.xpt'; PROC COPY IN = work OUT = x;
Read transport read_xpt("f.xpt") LIBNAME x XPORT 'f.xpt'; PROC COPY IN = x OUT = work;
Bare SAS date as.Date(x, origin = "1960-01-01") Apply a format: FORMAT x DATE9.;

29.11 Further reading

  • (Delwiche & Slaughter, 2019), The Little SAS Book, the standard introduction.
  • SAS documentation at documentation.sas.com, the procedure reference, in particular the ‘Details’ sections on parameterization and default options.
  • The mmrm package vignettes (Sabanes Bove et al., 2026), which compare its results with PROC MIXED setting by setting.

29.12 Prerequisites answers

  1. A DATA step reads, creates, or transforms a SAS dataset row by row, using an implicit loop over records. PROC steps consume existing datasets and produce listings, tables, graphs, or statistical output. A PROC step does not create new observations (with rare exceptions). The typical workflow alternates: DATA step to shape the data, PROC step to analyze it.
  2. In SAS, PROC MEANS or PROC SUMMARY produces analogous output (N, mean, SD, min, max, quantiles). In R, summary(df) gives a mixed-type summary across columns; skimr::skim(df) is closer to PROC MEANS output. PROC UNIVARIATE gives more detail (quantiles, skewness, kurtosis).
  3. The SAS transport file (.xpt, SAS transport version 5) is the long-standing interchange format and is required for FDA submissions. In R, the haven package reads and writes .xpt and reads native .sas7bdat: haven::read_xpt(), haven::write_xpt(), haven::read_sas().