A little announcement. A lot to explore.

Happy learning!

Explore lessons, including SAS & R programs and practice data.

Search lessons

Type at least 3 characters to see matching lessons.

Open SAS ↗Open R ↗
← SASnRLAG Within BY Groups

Introduction

  • Per-subject change from previous visit is one of the most common ADaM derivations — and it is where most LAG bugs happen in SAS.
  • The core problem: SAS LAG() does not automatically reset at BY-group boundaries. If we forget to guard with first.var, the first row of a new subject picks up the last row of the previous subject.
  • R tidyverse handles this automatically — group_by() + lag() resets at each group boundary with no extra code.
  • Base R achieves the same result with ave() and a custom lag function that runs independently within each group.
  • This lesson demonstrates the SAS bug, the SAS fix, and both R equivalents on a small vital-signs dataset.

LAG Within BY Groups