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 ↗
← SASnRRetain last non-missing value

Introduction

  • Last Observation Carried Forward (LOCF) is a common imputation: when a visit value is missing, substitute the most recent non-missing value from the same subject.
  • LOCF lets downstream summaries treat the visit as if it had the carried value, and keeps the full row count of the original dataset.
  • SAS does this with a DATA step that RETAINs a helper variable and updates it only on non-missing rows.
  • Tidyverse uses group_by(usubjid) %>% fill(score, .direction = "down") to propagate non-NA values forward within each group.
  • Base R uses ave() with a small loop that walks each subject's vector and replaces NAs with the last seen non-NA value.
  • This lesson keeps an orig_score column as a snapshot so we can see where the fill actually happened.

Retain last non-missing value