SAS to R dictionary
For readers who know SAS: each row is a SAS idiom, its R form in this book, and where the book explains it. Use the search of the site (Ctrl+K) to find a SAS keyword.
Part I: chapters 1 to 4
Section titled “Part I: chapters 1 to 4”| SAS | R | Where |
|---|---|---|
DATA new; SET old(KEEP=a b); RUN; |
new <- old |> select(a, b) |
ch 1, ch 2 |
PROC FREQ; TABLES arm; |
count(arm) |
ch 1 |
WHERE / subsetting IF |
filter() |
ch 2 |
| assignment statement | mutate() |
ch 2 |
IF ... THEN ...; ELSE ...; |
if_else(), case_when() |
ch 1, ch 2 |
%LET arm = Placebo; |
arm <- "Placebo" |
ch 1 |
PROC MEANS + merge back (value of all rows) |
mutate(m = mean(x)) |
ch 2 |
MISSING(x) |
is.na(x) |
ch 2 |
missing text " " |
NA, or "" in data read from SAS files |
ch 2 |
DATALINES |
tibble::tribble() |
ch 2 |
PROC IMPORT / INFILE ... DSD |
readr::read_csv() |
ch 2 |
FILE / PUT to a CSV, PROC EXPORT |
readr::write_csv() |
ch 2 |
permanent data set mylib.x |
saveRDS(x, "path/x.rds"), readRDS() |
ch 2 |
WORK library |
tempdir() |
ch 2 |
INPUT(dtc, ?? E8601DA.) |
as.Date(dtc, format = "%Y-%m-%d") |
ch 2 |
| impute a partial start date early | lubridate::ymd(dtc, truncated = 2) |
ch 2 |
INTNX("MONTH", d, 0, "E") |
lubridate::rollforward(d) |
ch 2 |
MDY(12, 31, YEAR(d)) |
lubridate::make_date(year(d), 12, 31) |
ch 2 |
PROC FORMAT for groups and their order |
case_when() + factor(x, levels = ...) |
ch 2 |
| the log | the console: messages, warnings, errors | ch 2 |
PROC CONTENTS |
glimpse(), class() |
ch 3 |
PUT(x, best.) |
as.character(x) |
ch 3 |
INPUT(x, best.) |
as.numeric(x) |
ch 3 |
SCAN(x, 3, "-") |
stringr::str_split_i(x, "-", 3) |
ch 3 |
LABEL x = "..."; |
attr(x, "label") <- "..." |
ch 3 |
SUBSTR(x, 4, 3) |
str_sub(x, 4, 6) (start and end) |
ch 3 |
FIND(x, "pain", "i") > 0 |
str_detect(x, regex("pain", ignore_case = TRUE)) |
ch 3 |
TRANWRD(x, a, b) |
str_replace_all(x, fixed(a), b) |
ch 3 |
CATS() / CATX() |
str_c() |
ch 3 |
UPCASE() / LOWCASE() |
str_to_upper() / str_to_lower() |
ch 3 |
STRIP(COMPBL(x)) |
str_squish(x) |
ch 3 |
STRIP(x) |
str_trim(x) |
ch 3 |
PUT(x, Z6.) |
str_pad(x, 6, pad = "0") |
ch 3 |
PUT(x, 5.1) |
sprintf("%.1f", x) |
ch 3 |
PUT(d, DATE9.) |
toupper(format(d, "%d%b%Y")) |
ch 3 |
YEAR(d), MONTH(d) |
lubridate::year(d), month(d) |
ch 3 |
YRDIF(a, b, "ACT/ACT") |
time_length(interval(a, b), "years") |
ch 3 |
SUM(a, b) (ignores missing) |
sum(a, b, na.rm = TRUE) |
ch 3 |
ROUND(x, 0.1) (half away from zero) |
a round-half-up function; round() rounds half to even |
ch 3 |
PRXMATCH("/^\d{4}$/", x) > 0 |
str_detect(x, "^\\d{4}$") |
ch 3 |
PROC SORT; BY a DESCENDING b; |
arrange(a, desc(b)) |
ch 4 |
PROC SORT NODUPKEY |
arrange() + distinct(..., .keep_all = TRUE) |
ch 4 |
DUPOUT= |
filter(duplicated(pick(keys))) |
ch 4 |
FIRST.x / LAST.x |
row_number() == 1 / row_number() == n() in a group |
ch 4 |
BY x; IF FIRST.x; |
slice_head(n = 1, by = x) |
ch 4 |
LAG(x) |
dplyr::lag(x) |
ch 4 |
RETAIN base; (carry baseline) |
mutate(BASE = x[flag %in% "Y"], .by = USUBJID) |
ch 4 |
sum statement n + 1; |
cumsum() |
ch 4 |
RETAIN worst; worst = MAX(worst, x); |
cummax(x) |
ch 4 |
RETAIN last non-missing value (LOCF) |
tidyr::fill(x, .direction = "down") |
ch 4 |
IF LAST.x THEN OUTPUT; (one row per group) |
summarise(..., .by = x) |
ch 4 |
Part I: chapters 5 to 8
Section titled “Part I: chapters 5 to 8”| SAS | R | Where |
|---|---|---|
SET a b; |
bind_rows(a, b) |
5.2 |
SET a(IN=ina) b; with a source variable |
bind_rows(A = a, B = b, .id = "SOURCE") |
5.2 |
MERGE a(IN=ina) b(IN=inb); BY key; IF ina AND inb; |
inner_join(a, b, by = join_by(key)) |
5.3 |
MERGE ...; BY key; IF ina; |
left_join(a, b, by = join_by(key)) |
5.3 |
MERGE ...; BY key; (all records) |
full_join(a, b, by = join_by(key)) |
5.3 |
WHERE key IN (SELECT key FROM b) |
semi_join(a, b, by = join_by(key)) |
5.4 |
IF ina AND NOT inb; / NOT IN (SELECT ...) |
anti_join(a, b, by = join_by(key)) |
5.4 |
RENAME= to avoid an overwrite in MERGE |
.x / .y, or suffix = c("_a", "_b") |
5.5 |
| NOTE: MERGE statement has more than one data set with repeats of BY values | Warning: many-to-many relationship | 5.6 |
PROC SORT NODUPKEY check before a MERGE |
relationship = "many-to-one" |
5.7 |
PROC TRANSPOSE of SUPPDM, then MERGE |
pivot_wider() of SUPPDM, then left_join() |
5.8 |
PROC CONTENTS |
glimpse(), names(), sapply(df, attr, "label") |
6.1 |
PROC PRINT DATA=x(OBS=5); |
print(x, n = 5) |
6.1 |
PROC FREQ; TABLES a*b / LIST OUT=; |
count(a, b) |
6.2 |
TABLES x / MISSING; |
count(x) (counts NA by default) |
6.2 |
PROC MEANS; CLASS g; VAR x; OUTPUT OUT=; |
group_by(g) |> summarise(mean = mean(x)) |
6.3 |
| Statistics skip missing values | mean(x, na.rm = TRUE) |
6.3 |
Q1 with PCTLDEF=5 |
quantile(x, 0.25, type = 2) |
6.3 |
SELECT COUNT(DISTINCT usubjid) INTO :n1-:n3 |
count(TRT01A, name = "BIGN") |
6.4 |
| Remerge of a summary statistic in PROC SQL | group_by(g) |> mutate(stat = mean(x)) |
6.5 |
COUNT(DISTINCT usubjid) |
n_distinct(USUBJID) |
6.6 |
UNION, INTERSECT, EXCEPT |
union(), intersect(), setdiff() |
6.8 |
WHERE x LIKE '%TEXT%' |
filter(str_detect(x, fixed("TEXT"))) |
6.9 |
ARRAY + DO i = 1 TO DIM() |
mutate(across(cols, rule, .names = "{.col}N")) |
7.1 |
SELECT; WHEN ...; OTHERWISE ...; END; |
case_when(cond ~ value, .default = other) |
7.2 |
DO adt = start TO end; OUTPUT; END; |
rowwise() |> reframe(ADT = seq(start, end, by = "day")) |
7.3 |
PROC TRANSPOSE; BY id; ID name; VAR value; |
pivot_wider(id_cols, names_from, values_from) |
7.4 |
PREFIX= / SUFFIX= of PROC TRANSPOSE |
names_prefix = / names_glue = |
7.4 |
PROC TRANSPOSE wide to long, NAME=, RENAME=(col1=aval) |
pivot_longer(cols, names_to, values_to) |
7.6 |
PROC FORMAT CNTLIN= lookup |
a lookup table and left_join() |
7.7 |
VALUE format for a few codes |
named vector: c(Pbo = 0, Xan_Lo = 54)[code] |
7.7 |
VALUE format with NOTSORTED, ORDER=DATA |
factor(x, levels = ..., labels = ...) |
7.8 |
INVALUE that turns text into a sort number |
as.integer(factor(x, levels = ...)) |
7.8 |
Hash object FIND() |
table$value[match(x, table$key)] |
7.9 |
%MACRO name(param=default); |
name <- function(param = default) { } |
8.1 |
&var. as a variable name in a macro |
{{ var }} in a function |
8.2 |
| A variable name in a macro variable | .data[[var]] |
8.4 |
%PUT ERROR: ...; %GOTO finish; |
cli::cli_abort("..."), stopifnot() |
8.5 |
%INCLUDE of a macro file |
source("R/file.R") |
8.5 |
%DO i = 1 %TO %SYSFUNC(COUNTW(&list.)); |
map(list, f), walk(list, f), for (v in list) |
8.6 |
SET out_1-out_3; after a macro loop |
list_rbind(map(...)) |
8.6 |
%PUT to the log |
cat(line, file = log, append = TRUE) |
8.7 |
Part II: ADaM
Section titled “Part II: ADaM”| SAS | R | Where |
|---|---|---|
PROC MEANS ... MIN= with CLASS usubjid |
summarise(TRTSDT = min(EXSTDT), .by = USUBJID) |
9.3 |
MAX= skips missing values; NMISS= counts them |
max(x) is NA when one value is NA; max(x, na.rm = TRUE) skips it |
9.3 |
COALESCE(a, b) |
coalesce(a, b) |
9.3 |
%m_merge(data=, add=, out=) |
left_join(data, add, relationship = "one-to-one") in a small function |
9.4 |
PROC TRANSPOSE ... ID qnam; VAR qval; |
tidyr::pivot_wider(names_from = QNAM, values_from = QVAL) |
9.4 |
PROC COMPARE BASE= COMPARE=; ID usubjid; |
diffdf::diffdf(base, compare, keys = "USUBJID") |
9.6 |
INPUT(xxdtc, E8601DA.) |
lubridate::ymd(xxdtc) or admiral derive_vars_dt() |
9.3 |
IF adt >= trtsdt THEN ady = adt - trtsdt + 1; ELSE ady = adt - trtsdt; |
as.numeric(ADT - TRTSDT) + if_else(ADT >= TRTSDT, 1, 0), or derive_vars_dy() |
10.1 |
BY usubjid; IF LAST.usubjid; among the rows before the first dose |
mutate(ABLFL = if_else(row_number() %in% last(which(can_be_base)), "Y", NA), .by = USUBJID) |
10.1 |
merge a one-row-per-subject baseline back with BY usubjid |
mutate(BASE = first(AVAL[ABLFL %in% "Y"]), .by = USUBJID), or derive_var_base() |
10.1 |
%m_baseline(by=usubjid paramcd atptn, ...) |
derive_baseline(by = c("USUBJID", "PARAMCD", "ATPTN"), order = c("ADT", "VSSEQ")) |
10.2 |
IF aval < anrlo THEN anrind = "LOW"; ELSE IF ... |
case_when(AVAL < ANRLO ~ "LOW", AVAL > ANRHI ~ "HIGH", !is.na(AVAL) ~ "NORMAL"), or derive_var_anrind() |
10.5 |
astdt = MDY(mm, 1, yy); astdtf = "D"; |
ymd(paste0(AESTDTC, "-01")), or derive_vars_dt(highest_imputation = "M", min_dates = exprs(TRTSDT)) |
11.2 |
PROC SORT; BY usubjid astdt aeseq; then IF FIRST.usubjid |
arrange(ASTDT, AESEQ), then mutate() with row_number() == 1 and .by = USUBJID, or derive_var_extreme_flag(mode = "first") |
11.2 |
IF astdt >= trtsdt THEN trtemfl = "Y"; |
if_else(ASTDT >= TRTSDT, "Y", NA), or derive_var_trtemfl() |
11.2 |
%m_tte(events=, enddt=, censordt=) |
derive_param_tte(event_conditions = list(event_source(...)), censor_conditions = list(censor_source(...))) |
12.3 |
PROC LIFETEST; TIME aval*cnsr(1); STRATA trt01a; |
survival::survfit(Surv(AVAL, 1 - CNSR) ~ TRT01A) |
12.5 |
Part III: tables, listings, figures
Section titled “Part III: tables, listings, figures”| SAS | R | Where |
|---|---|---|
CALL SYMPUTX for the big N |
count(TRT, name = "N"), then left_join() |
13.1 |
OUTPUT; trt01an = 99; OUTPUT; (Total column) |
bind_rows(data, mutate(data, TRT01A = "Total")) |
13.1 |
| PROC MEANS for a demographics table | group_by(), summarise() with sprintf() |
13.2 |
| PROC TRANSPOSE of the layout | pivot_wider(names_from = TRT, values_from = value) |
13.2 |
grid DATA step, IF MISSING(n) THEN n = 0 |
complete(..., fill = list(n = 0)) |
13.2 |
ROUND(x, 0.1), format 5.1 |
round_half_up(x, 1) (not round()) |
13.3 |
PROC SORT NODUPKEY; BY trtan aebodsys usubjid; |
distinct(TRT, AEBODSYS, USUBJID) |
13.4 |
study table macros (%m_desc, %m_freq) |
gtsummary::tbl_summary() |
13.5 |
| AE table macro | gtsummary::tbl_hierarchical(id = USUBJID, denominator = adsl) |
13.5 |
PROC REPORT COLUMN / DEFINE, PROC TABULATE |
rtables: basic_table() |> split_cols_by() |> analyze(), build_table() |
13.6 |
| PROC COMPARE of two tables | join the cells and count the same text | 13.7 |
ODS HTML |
gt::gtsave() |
13.8 |
ODS RTF with PROC REPORT |
flextable + officer::body_add_flextable() |
13.8 |
PROC REPORT DEFINE x / ORDER in a listing |
flextable::merge_v(j = "x") |
14.1 |
PROC REPORT FLOW WIDTH=30 |
flextable::width() (text wraps in the cell) |
14.1 |
PROC MEANS STDERR= |
sd(x) / sqrt(n()) |
14.2 |
PROC SGPLOT SERIES, SCATTER YERRORLOWER= YERRORUPPER=, REFLINE |
geom_line(), geom_errorbar(), geom_hline() |
14.3 |
| ODS GRAPHICS image file | ggsave("f.png", fig, width = 8, height = 5) |
14.3 |
PROC LIFETEST TIME aval * cnsr(1); STRATA trtan; |
survfit(Surv(AVAL, 1 - CNSR) ~ TRT) |
14.4 |
PROC LIFETEST PLOTS=SURVIVAL(ATRISK=...) |
ggsurvfit() + add_risktable(times = ...) |
14.5 |
ATTRIB from the specification, LIBNAME x XPORT + PROC COPY |
xportr_type(), xportr_length(), xportr_label(), xportr_write() |
14.6 |
LIBNAME x XPORT to read |
haven::read_xpt() |
14.6 |
Parts IV and V: quality and advanced functions
Section titled “Parts IV and V: quality and advanced functions”| SAS | R | Where |
|---|---|---|
PROC COMPARE BASE=prod COMPARE=qc; ID usubjid; RUN; |
diffdf::diffdf(prod, qc, keys = "USUBJID") |
15.2 |
&SYSINFO. after PROC COMPARE |
diffdf_has_issues(res), res$NumDiff |
15.4 |
PROC COMPARE ... CRITERION=1E-8 |
diffdf(..., tolerance = 1e-8) (the default is about 1.5e-08) |
15.5 |
%logcheck on a log file |
withCallingHandlers(source(file), warning = ..., message = ...) |
15.9 |
NOTE: MERGE statement has more than one data set with repeats of BY values |
the dplyr warning Detected an unexpected many-to-many relationship | 15.9 |
PROC SQL checks with NOT IN (SELECT ...) |
anti_join() and a tribble() of counts |
16.3 |
PROC FREQ of a decision variable |
count(data, WTBLSRC) |
16.4 |
%LOCAL macro variable |
a name made inside a function: always local | 17.2 |
&var. in a macro that writes MEAN(&var.) |
{{ var }} in a function, or enquo() and !! |
17.5 |
&var._gt&limit. as a variable name |
"{{ var }}_GT{limit}" := |
17.6 |
%STR, %NRSTR, %BQUOTE, %SUPERQ |
not needed: a value is never code | 17.7 |
CALL SYMPUTX(CATS("pcd", _N_), paramcd) and &&pcd&i. |
codes <- distinct(advs, PARAMCD)$PARAMCD, then codes[i] |
18.1 |
%DO i = 1 %TO &nparam.; with WHERE paramcd = "&&pcd&i." |
split(data, data$PARAMCD) |> map(f) |
18.2 |
cont=age|Age (years)|0#... with %QSCAN |
a tribble() of settings and pmap() |
18.4 |
PROC CONTENTS ... OUT= as a specification |
map_chr(data, \(x) attr(x, "label")) |
18.6 |
CALL EXECUTE, DOSUBL |
map(); code as text with eval(parse(text = )) only as the last choice |
18.7 |
%STR(ERR)OR: [MACRO] ... and %GOTO finish |
cli::cli_abort("...") |
19.1 |
an autocall library and SASAUTOS |
a package folder and pkgload::load_all() |
19.2 |
| a test harness that counts ERROR lines per test case | testthat::test_that() with expect_error(), testthat::test_dir() |
19.4 |
OPTIONS MPRINT MLOGIC SYMBOLGEN; |
debugonce(f) or browser() |
19.6 |
Part VI: DataStep Studio for SAS and for R
Section titled “Part VI: DataStep Studio for SAS and for R”| SAS | R | Where |
|---|---|---|
SAS log (NOTE: The data set WORK.ADSL has 254 observations ...) |
the DataStep Studio for R log (NOTE: adsl has 254 rows and 6 columns) |
ch 20 |
NOTE: Missing values were generated |
New: WGTGR (1 missing) in the log; rule missing_values |
ch 20 |
NOTE: MERGE statement has more than one data set with repeats of BY values |
the suspicious log rule join: rows went up in a join |
ch 20 |
NOTE: Invalid numeric data |
the suspicious log rule coercion: NAs introduced by coercion |
ch 20 |
Run To Line (Ctrl+Alt+Up) |
Run to Line (Cmd/Ctrl+Alt+T), dsr run --to-line |
ch 20 |
| a new SAS session, empty WORK | dsr stop --session, dsr start |
ch 20 |
| Run in Batch | dsr batch a.R b.R |
ch 26 |
viewer WHERE trtemfl = "Y" AND aesev = "SEVERE" |
viewer WHERE TRTEMFL == "Y" & AESEV == "SEVERE" |
ch 21 |
| viewer SQL button | viewer R code button, dsr query --code |
ch 21 |
. missing, smaller than every number |
NA, not a value: is.na() |
ch 21 |
| keyboard macro + Tab | snippet + Tab | ch 22 |
| Format SAS Program | Format R Program (Ctrl+Shift+A), dsr format |
ch 22 |
Enlarge / Optimize Macro Call (Ctrl+Shift+E / Ctrl+Shift+O) |
Enlarge / Optimize Function Call (same keys), dsr call |
ch 22 |
Open Macro Definition (Cmd/Ctrl+click) |
Go to Definition (Cmd/Ctrl+click), dsr def |
ch 22 |
| DATA step debugger: watch the PDV | dsr pipe file.R:line: the rows at each step of a pipeline |
ch 23 |
IN= flags of a MERGE |
@pipe[k]:unmatched:x, @pipe[k]:unmatched:y |
ch 23 |
breakpoint condition usubjid = "01-701-1015" |
dsr pipe ... --follow 01-701-1015 |
ch 23 |
%pry |
pry() |
ch 24 |
%pry(when=&i. = 3) |
pry(when = sev == "SEVERE") |
ch 24 |
%pry(rescue=Y) |
nothing to write: an error keeps its frames open (dsr pry stack) |
ch 24 |
vt work._sev, freq trta at a %pry stop |
dsr pry eval 'dplyr::count(sub, TRT01A)', dsr query @pry:sub |
ch 24 |
watch &nsub |
watch nsub |
ch 24 |
PROC SORT BY usubjid visit; (visit names sort as text) |
arrange(USUBJID, VISIT): the same trap; sort by VISITNUM |
ch 24 |
| macro debugger: F5, F10, F11, Shift+F11 | R debugger: F5, F10, F11, Shift+F11 | ch 25 |
Edit Condition &i. = 3 |
Edit Condition any(age == 65) |
ch 25 |
%assert_eq tests of a macro |
testthat tests, dsr test |
ch 26 |
macro coverage ×N |
dsr test --coverage, dsr coverage |
ch 26 |
SAS Pry terminal: vt sdtm.cm, profile |
dsr describe cm, dsr profile cm |
ch 26 |
dups usubjid |
dsr dups adae --key USUBJID |
ch 26 |
Found an error or have a question? Write to datastep.studio@gmail.com· Every program runs in DataStep Studio for R, the R extension for VS Code and Positron.
Data: the CDISC pilot study (cdiscpilot01), from the R packagespharmaversesdtm andpharmaverseadam (Apache License 2.0).
R is a project of the R Foundation. SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. This book is not affiliated with or endorsed by SAS Institute Inc. or the R Foundation. CDISC, SDTM and ADaM are trademarks of the Clinical Data Interchange Standards Consortium.
© 2026 DataStep Labs. All rights reserved.