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

Create a macro variable and use it in open code


Lesson Description
-
  • Sometimes, we want to work with the concept of "Create a macro variable 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.
*=============================================================================;
* Create sample ADSL data;
*=============================================================================;

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;

*=============================================================================;
* Define macro variable and use in filter;
*=============================================================================;

%let trtp_filter = Placebo;

data adsl_filtered;
    set adsl;
    if trtp = "&trtp_filter.";
run;
library(tidyverse)

#==============================================================================
# Create sample ADSL data
#==============================================================================


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"
)

#==============================================================================;
#Create an object and use it's value in filter function;
#==============================================================================;

trt_filter <- "Placebo"

adsl_filtered <- adsl %>% 
  filter(trt01p==trt_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
)

trt_filter <- "Placebo"

adsl_filtered <- adsl[adsl$trt01p == trt_filter, ]
  • Store a filter value in an object.
  • Use logical indexing to subset rows.