Back to Practice
#0209

Order Factor Levels in R

EasyR15 min10 XP

Problem

Given size labels small, medium, and large, create an ordered factor with that order.

Why This Matters

R often sorts text alphabetically unless factor levels tell it the meaningful order.

Examples

Example 1
Inputmedium, small, large, small
Outputordered levels: small < medium < large

The values keep their row order, but the factor levels now have a meaningful rank.

Constraints

  • Return the exact requested result.
  • Handle common edge cases.
  • Keep the solution readable before optimizing.
CodeR
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Inputmedium, small, large, small
Expectedordered levels: small < medium < large

The values keep their row order, but the factor levels now have a meaningful rank.

Hidden Test Categories
empty or minimal inputrepeated valueslarger realistic input