Question Details

No question body available.

Tags

r dplyr

Answers (1)

February 3, 2026 Score: 5 Rep: 34,254 Quality: Medium Completeness: 80%

You can use an if ... else block:

if (nrow(p75) < 1) {
  NAcharacter
} else {
  casewhen(
    cenmean > 0.75 ~ "BDL",
    TRUE ~ sprintf(p75$obs, fmt = "%.1f")
  )
}

or

casewhen(
  nrow(p75) < 1   ~ NAcharacter,
  cenmean > 0.75  ~ "BDL",
  TRUE ~ if(nrow(p75) == 0) NAcharacter else sprintf(p75$obs, fmt = "%.1f")
)

But why is this happening?

It is because case_when() is vectorized. Internally, it must resolve a single output vector. To do this, it inspects every RHS argument to determine the output's common type and length. Because sprintf(character(0)) returns a vector of length 0, the function treats the entire operation as zero-length.

I have answered a similar question about is.na() with some details that also apply to here.