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

Find Maximum Value Across Multiple Variables in Each Row


Lesson Description
-
  • Sometimes, we want to work with the concept of "Find Maximum Value Across Multiple Variables in Each Row" 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.

 


data lab; 
input usubjid hgb_v1 hgb_v2 hgb_v3; 
datalines
1001 12.5 13.1 12.8 
1002 13.0 14.0 13.5 
1003 11.2 11.8 12.0 

run

data lab02; 
   
set lab; 
   maxval = max(of hgb_v1--hgb_v3); 
run;

 

  • The dataset `lab` contains hemoglobin values for three visits. `max(of hgb_v1--hgb_v3)` computes the maximum across the specified variables for each row.
  • The resulting value is stored in `maxval` for each subject.
lab <- tribble(
  ~USUBJID, ~HGB_V1, ~HGB_V2, ~HGB_V3,
  1001,     12.5,     13.1,    12.8,
  1002,     13.0,     14,      13.5,
  1003,     11.2,     11.8,    12.0
)

lab01 <- lab %>% 
  mutate(
    maxval=max(HGB_V1,HGB_V2,HGB_V3)
  )

lab02 <- lab %>% 
  rowwise() %>% 
  mutate(
    maxval=max(HGB_V1,HGB_V2,HGB_V3)
  )
  • The dataset `lab` includes hemoglobin results across three visits. `mutate(maxval = max(...))` without `rowwise()` gives a column-wise maximum, which is incorrect for row-level analysis. `rowwise()` allows the `max()` function to work across values in a row. `ungroup()` restores the dataset to a regular tibble.
lab <- data.frame(
  USUBJID = c(1001, 1002, 1003),
  HGB_V1 = c(12.5, 13.0, 11.2),
  HGB_V2 = c(13.1, 14, 11.8),
  HGB_V3 = c(12.8, 13.5, 12.0)
  , stringsAsFactors = FALSE
)

lab01 <- lab

lab01$maxval <- pmax(lab01$HGB_V1, lab01$HGB_V2, lab01$HGB_V3)

lab02 <- lab

lab02$maxval <- apply(lab02[, c("HGB_V1", "HGB_V2", "HGB_V3")], 1, max)
  • pmax() computes row-wise maxima across vectors.
  • apply(..., 1, max) does the same for selected columns.