Announcement Icon Online training class for Clinical R programming batch starts on Monday, 02Feb2026. Click here for details.

Create a macro variable to store list of values and use it in open code


Lesson Description
-
  • Sometimes, we want to work with the concept of "Create a macro variable to store list of values and use it in open code" in a clear, repeatable way.
  • This lesson walks through a simple example and shows the key steps.
  • We will see one approach on how we can do it in SAS and R.

*==============================================================================;
*Macro variable to store a list of values;
*==============================================================================;

data adsl;
    input usubjid $ trtp $ age sex $;
    datalines;
SUBJ001 Placebo 67 M
SUBJ002 DrugA   59 F
SUBJ003 Placebo 72 F
SUBJ004 DrugB   65 M
SUBJ005 Placebo 60 F
;
run;

%let age_filter = %str(59,72);

data adsl_filtered;
    set adsl;
    if age in (&age_filter.);
run;

#==============================================================================;
#List of values in macro variable;
#==============================================================================;
library (tidyverse)

adsl <- tribble(
  ~usubjid, ~trt01p,     ~age, ~sex,
  "SUBJ001", "Placebo", 67,   "M",
  "SUBJ002", "DrugA",    59,   "F",
  "SUBJ003", "Placebo", 72,   "F",
  "SUBJ004", "DrugB",    65,   "M",
  "SUBJ005", "Placebo", 60,   "F"
)

age_filter <- c(59,72)

adsl_filtered <- adsl %>% 
  filter(age %in% age_filter)
adsl <- data.frame(
  usubjid = c("SUBJ001", "SUBJ002", "SUBJ003", "SUBJ004", "SUBJ005"),
  trt01p = c("Placebo", "DrugA", "Placebo", "DrugB", "Placebo"),
  age = c(67, 59, 72, 65, 60),
  sex = c("M", "F", "F", "M", "F")
  , stringsAsFactors = FALSE
)

age_filter <- c(59, 72)

adsl_filtered <- adsl[adsl$age %in% age_filter, ]
  • %in% filters rows where age is in the specified vector.