LEAVE stops the current DO loop immediately and carries on with the statement after its END. CONTINUE skips the rest of the current iteration and starts the next one. For long IF-THEN-ELSE chains, a SELECT group or a user-defined format is usually shorter and easier to check.Array loops over visits are everywhere in clinical programming: the first visit that meets a lab criterion, the number of non-missing assessments, a flag across a row of questionnaire items. Two small statements make these loops shorter and clearer, and two alternatives to IF-THEN-ELSE make the recoding around them easier to review. All examples use one small wide lab dataset.
Test data: ALT as a multiple of ULN, six visits
data hep;
input usubjid $ altx1-altx6;
datalines;
1001 0.8 1.1 3.4 2.0 3.9 1.2
1002 0.9 . 1.0 1.2 . 0.7
1003 1.5 3.1 . . . .
;
run;
Each altxN is ALT divided by the upper limit of normal at visit N. Subject 1003 discontinued after visit 2.
LEAVE: stop at the first match
Task: find the first visit where ALT reached 3 x ULN.
data first3x;
set hep;
array altx{6} altx1-altx6;
first3x = .;
do v = 1 to 6;
if altx{v} >= 3 then do;
first3x = v;
leave; /* jump to the statement after END */
end;
end;
drop v;
run;
library(dplyr)
first_at_least <- function(x, limit) {
for (v in seq_along(x)) {
if (!is.na(x[v]) && x[v] >= limit) return(v)
}
NA_integer_
}
# loop version, for comparison with SAS
first3x <- hep %>%
rowwise() %>%
mutate(first3x = first_at_least(c_across(altx1:altx6), 3)) %>%
ungroup()
# the usual R way: no loop at all
which(c(0.8, 1.1, 3.4, 2.0, 3.9, 1.2) >= 3)[1] # 3
Expected result:
| USUBJID | first3x | Why |
|---|---|---|
| 1001 | 3 | 3.4 at visit 3. Visit 5 (3.9) is never checked. |
| 1002 | . | No value reaches 3. |
| 1003 | 2 | 3.1 at visit 2. |
Without LEAVE, subject 1001 would get 5, the last visit at or above 3, because the loop keeps overwriting first3x. That is a quiet bug: the program runs and the value looks reasonable.
A side effect worth knowing: after a loop that runs to the end, the index is one past the stop value (here v = 7). After LEAVE, it holds the iteration where the loop stopped.
In R, break is the equivalent of LEAVE. The function above uses return(), which also ends the loop. For a plain vector, which(x >= 3)[1] does the same job and ignores NA.
CONTINUE: skip this iteration
Task: count the visits with a result, and how many of those were above ULN.
data counts;
set hep;
array altx{6} altx1-altx6;
n_obs = 0;
n_high = 0;
do v = 1 to 6;
if missing(altx{v}) then continue; /* go to the next v */
n_obs = n_obs + 1;
if altx{v} > 1 then n_high = n_high + 1;
end;
drop v;
run;
counts <- hep %>%
mutate(
n_obs = rowSums(!is.na(pick(altx1:altx6))),
n_high = rowSums(pick(altx1:altx6) > 1, na.rm = TRUE)
)
# loop form uses next, the R version of CONTINUE:
# for (v in seq_along(x)) { if (is.na(x[v])) next; ... }
| USUBJID | n_obs | n_high |
|---|---|---|
| 1001 | 6 | 5 |
| 1002 | 4 | 1 |
| 1003 | 2 | 2 |
The counters are set to 0 before the loop on every record. If you write them as sum statements (n_obs + 1;) instead, they are retained across subjects, and without the reset the counts keep growing.
pick() needs dplyr 1.1.0 or later. On older versions use across() inside rowSums().
Rules for both statements
- They work in iterative
DO,DO WHILEandDO UNTILloops. - In nested loops they act on the innermost loop only.
LEAVEcan also end aSELECTgroup.CONTINUEis for loops only.- They do not end the DATA step iteration. Code after the loop still runs, and the record is still output.
Alternatives to long IF-THEN-ELSE chains
SELECT for one variable with many values
select (aesev);
when ('MILD') aesevn = 1;
when ('MODERATE') aesevn = 2;
when ('SEVERE') aesevn = 3;
otherwise aesevn = .;
end;
Each value is visible at a glance, and the variable name is written once instead of in every ELSE IF. Keep the OTHERWISE. If no WHEN matches and there is no OTHERWISE, the step stops with an "Unsatisfied WHEN clause and no OTHERWISE statement" error. That is useful during development, but an unexpected value in a production run then stops your program.
SELECT without an expression, and the missing-value trap
length agegr1 $5;
select;
when (missing(age)) agegr1 = ' ';
when (age < 18) agegr1 = '<18';
when (age < 65) agegr1 = '18-64';
otherwise agegr1 = '>=65';
end;
The first WHEN is not decoration. SAS treats a missing number as smaller than any value, so age < 18 is true for a missing age. Without that line, a subject with no age is grouped as under 18. The same trap applies to IF-THEN-ELSE.
A format for groupings used in many programs
proc format;
value agegrf
. = ' '
low -< 18 = '<18'
18 -< 65 = '18-64'
65 - high = '>=65';
run;
data adsl2;
set adsl;
length agegr1 $5;
agegr1 = put(age, agegrf.);
run;
The grouping now lives in one place, and every program that uses the format gets the same cut-offs. For numeric formats, LOW does not include missing values, which is why missing is mapped on its own line.
IFC and IFN for a simple either/or
length saffl $1;
saffl = ifc(not missing(trtsdt), 'Y', 'N');
IFC returns a character value and IFN a numeric one. Declare the length first, otherwise the new variable gets a long default length. Also note that both result arguments are evaluated whatever the condition is, so don't put an expression there that fails on some records.
The R equivalents
adsl2 <- adsl %>%
mutate(AGEGR1 = case_when(
AGE < 18 ~ "<18",
AGE < 65 ~ "18-64",
AGE >= 65 ~ ">=65"
))
In R, NA < 18 is NA, not TRUE, so a missing age matches no condition and stays NA. That is the opposite of SAS. Be careful with a catch-all .default or TRUE ~ line, though: it will catch the missing ages too.
Common mistakes
- No LEAVE when you want the first match. The loop keeps going and you get the last match.
- Expecting LEAVE to end the record. It only ends the loop. Use
DELETEor a subsetting IF to drop the record. - Counters that are not reset. Set them before the loop, or use plain assignment instead of the sum statement.
- Missing values falling into the lowest group. Test for missing first in IF, SELECT and formats.
- SELECT without OTHERWISE in production code. One unexpected value stops the run.
Try it yourself: last visit with a result
Write a loop that finds the last visit with a non-missing altx value for each subject, stopping as soon as it finds one. What are the expected values?
Answer: Loop backwards and leave on the first non-missing value:
lastvis = .;
do v = 6 to 1 by -1;
if not missing(altx{v}) then do;
lastvis = v;
leave;
end;
end;
Expected: 1001 = 6, 1002 = 6, 1003 = 2. In R: max(which(!is.na(x))), which gives the same values.
Quick check
1. What happens after LEAVE runs inside a DO loop?
LEAVE exits the loop only. The rest of the step still runs for that record.
2. In SAS, what does if age < 18 return for a missing age?
Missing numeric values sort below all numbers, so the comparison is true. Check for missing first.
Frequently asked questions
How do I exit a DO loop early in SAS?
Use the LEAVE statement, usually inside an IF-THEN DO block. It ends the innermost loop and continues after its END.
What is the SAS equivalent of break and continue?
LEAVE is the equivalent of break and CONTINUE is the equivalent of continue (or next in R).
Is SELECT faster than IF-THEN-ELSE in SAS?
Any speed difference is small for typical clinical datasets. Choose SELECT because it is easier to read and review.
When should I use a format instead of IF-THEN-ELSE?
When the same grouping is used in more than one program or output, such as age groups or lab categories. The cut-offs then live in one place.
LEAVEexits the loop,CONTINUEskips one iteration. Neither ends the record.- For "first visit that meets X", LEAVE is what makes it the first.
- SELECT with OTHERWISE, formats and IFC/IFN replace most long IF-THEN-ELSE chains.
- Missing numbers are smaller than everything in SAS. In R, comparisons with NA give NA. Test for missing explicitly in both.
Related: FIRST. and LAST. in SAS and R · LOCF in ADaM with SAS and R · SAS vs R for clinical trials