Converts a vector object to a categorical object, typically a column in a data frame.

as_category(
  x,
  labels = as.vector(c(na.omit(unique(x)))),
  na_values = NULL,
  as_factor = FALSE
)

Arguments

x

A vector object to be coerced to categorical.

labels

An optional vector of the unique values (as character strings) that x might have taken. The default is the unique set of values taken by as.character(x), sorted into increasing order of x. Note that this set can be specified as smaller than sort(unique(x)).

na_values

An optional vector of the unique values (as character strings) among labels, for which the value is considered as missing. The default is NULL. Note that this set can be specified as smaller than labels.

as_factor

Whether the output is a categorical variable (haven labelled object) or is a factor (labels and na_values will be lost, but the order of the levels will be preserved). FALSE by default.

Value

A vector with class haven_labelled.

Examples

{

library(dplyr)

##### Example 1: use madshapR_examples provided by the package
dataset <-
  madshapR_examples$`dataset_example` %>%
  mutate(prg_ever = as_category(prg_ever))
  
head(dataset$prg_ever)

###### Example 2: any data frame can be a dataset
cat_cyl <- as_category(mtcars[['cyl']])

head(cat_cyl)

}
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
#> <labelled<double>[6]>
#> [1] 6 6 4 6 8 6
#> 
#> Labels:
#>  value label
#>      6     6
#>      4     4
#>      8     8