inspect_categories checks if an object is eligible to be used as the levels of a factor. This can be useful to validate inputs in user-defined functions.

inspect_categories(x)

Arguments

x

An arbitrary object.

Value

inspect_categories does not return any output. There are two possible outcomes:

  • The call is silent if x is eligible to be used as the levels of a factor.

  • An informative error message is thrown otherwise.

Details

inspect_categories conducts a series of tests to check if x is eligible to be used as the levels of a factor. Namely, inspect_categories checks if:

  • x is NULL or empty.

  • x is atomic.

  • x has an eligible data type (logical, integer, double, character).

  • There are NA or NaN values in x.

  • There are repeated values in x.

See also

Examples

# Calls that pass silently:
x1 <- 1:5
x2 <- c("yes", "no")
x3 <- c(TRUE, FALSE)
x4 <- factor(c("smoker", "non-smoker"))
x5 <- factor(c("yes", "no", "yes"))
inspect_categories(x1)
inspect_categories(x2)
inspect_categories(x3)
inspect_categories(x4)
inspect_categories(levels(x5))

# Calls that throw informative error messages:
y1 <- c(1, 1:5)
y2 <- c("yes", "no", "yes")
y3 <- factor(c("yes", "no", "yes"))
try(inspect_categories(y1))
#> Error in inspect_categories(y1) : 
#>   Invalid argument: all element of y1 must be unique.
try(inspect_categories(y2))
#> Error in inspect_categories(y2) : 
#>   Invalid argument: all element of y2 must be unique.
try(inspect_categories(y3))
#> Error in inspect_categories(y3) : 
#>   Invalid argument: all element of y3 must be unique.
try(mylist <- list(
  NULL, numeric(0),
  complex(1), list(10), NaN, NA
))
try(inspect_categories(mylist[[1]]))
#> Error in inspect_categories(mylist[[1]]) : 
#>   Invalid argument: mylist[[1]] is NULL.
try(inspect_categories(mylist[[2]]))
#> Error in inspect_categories(mylist[[2]]) : 
#>   Invalid argument: mylist[[2]] is empty.
try(inspect_categories(mylist[[3]]))
#> Error in inspect_categories(mylist[[3]]) : 
#>   Invalid argument: the type of mylist[[3]] must be 'logical', 'integer', 'double' or 'character'.
try(inspect_categories(mylist[[4]]))
#> Error in inspect_categories(mylist[[4]]) : 
#>   Invalid argument: mylist[[4]] must be of an atomic type.
try(inspect_categories(mylist[[5]]))
#> Error in inspect_categories(mylist[[5]]) : 
#>   Invalid argument: there are NA or NaN values in mylist[[5]].
try(inspect_categories(mylist[[6]]))
#> Error in inspect_categories(mylist[[6]]) : 
#>   Invalid argument: there are NA or NaN values in mylist[[6]].