30-Day Course
Clinical SAS → R
Day 6 of 30·Data Manipulation

The DATA Step Reimagined: filter() & select()

Row and column selection move from WHERE/IF and KEEP/DROP to two readable dplyr verbs.

Learning objectives

  • 1Replace WHERE / IF subsetting with filter().
  • 2Replace KEEP / DROP / RENAME with select() and rename().
  • 3Chain operations with the native pipe |>.
  • 4Combine multiple conditions with &, | and %in%.

Key SAS® → R comparison

TaskSAS®R
Subset rowswhere age >= 18;filter(df, age >= 18)
Multiple conditionsif a=1 and b>0;filter(df, a == 1 & b > 0)
In a listif arm in ('A','B');filter(df, arm %in% c('A','B'))
Keep columnskeep usubjid age;select(df, usubjid, age)
Drop columnsdrop temp;select(df, -temp)
Renamerename old=new;rename(df, new = old)

Code examples

Filter and select in one pipeline
SAS®
data adsl_s;
  set adsl;
  where saffl='Y' and age>=18;
  keep usubjid age sex arm;
run;
R
adsl_s <- adsl |>
  filter(saffl == "Y", age >= 18) |>
  select(usubjid, age, sex, arm)

Note: Commas inside filter() are combined with AND, mirroring stacked WHERE conditions.

Explanation

dplyr reframes the DATA step as a sequence of explicit verbs. filter() keeps rows, select() keeps columns, and the pipe passes the result of one step into the next so the code reads top to bottom in the order operations happen.

Because each verb does exactly one thing, reviewers can reason about a pipeline far more easily than about a DATA step that mixes subsetting, keeping, and deriving in a single pass.

Practice exercise

Filter ADSL to the safety population aged 18+, keep USUBJID, AGE, SEX and ARM, and rename ARM to TRT01A using a single piped expression.