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: Access the Previous Row's Value

Introduction

  • Clinical programming often needs the value from the previous row — change-from-baseline, visit-over-visit differences, and shift tables all depend on it.
  • SAS provides the LAG() function, but it has a well-known trap: LAG always advances its internal queue, even when called inside a conditional IF. This lesson shows the bug and the fix.
  • In R tidyverse, dplyr::lag() inside mutate() does the same job without the conditional gotcha.
  • Base R builds the shifted vector manually with c(NA, head(x, -1)).
  • We use a small dataset of 3 subjects with 3 visits each and a numeric analysis value (AVAL) to demonstrate all three approaches.

LAG: Access the Previous Row's Value