nlevels
nlevels is a function in the R programming language that returns the number of levels in a factor or ordered factor. It provides a concise way to determine the size of the categorical domain of a variable. The argument x is typically a factor or an object that can be treated as one; nlevels returns an integer representing how many distinct levels exist in x. Conceptually, it is equivalent to length(levels(x)) since levels(x) yields the vector of all factor levels.
Usage and behavior: The function is part of base R and is primarily used when working with
Examples: nlevels(factor(c("low","high","low"))) returns 2. nlevels(ordered(c("A","B","A"))) returns 2.
Related functions: levels(x) retrieves the vector of level labels; as.factor or factor can convert other data
Notes: The function is part of the base stats package in R; for documentation, see the base