The base function as.factor() is not a generic, but this variant
is. Methods are provided for factors, character vectors, labelled
vectors, and data frames. By default, when applied to a data frame,
it only affects labelled columns.
# S3 method for data.frame as_factor(x, ..., only_labelled = TRUE) # S3 method for haven_labelled as_factor( x, levels = c("default", "labels", "values", "both"), ordered = FALSE, ... ) # S3 method for labelled as_factor( x, levels = c("default", "labels", "values", "both"), ordered = FALSE, ... )
| x | Object to coerce to a factor. |
|---|---|
| ... | Other arguments passed down to method. |
| only_labelled | Only apply to labelled columns? |
| levels | How to create the levels of the generated factor:
|
| ordered | If |
Includes methods for both class haven_labelled and labelled
for backward compatibility.
x <- labelled(sample(5, 10, replace = TRUE), c(Bad = 1, Good = 5)) # Default method uses values where available as_factor(x)#> [1] Good 4 Good 4 Bad Good Good Good 2 3 #> Levels: Bad 2 3 4 Good# You can also extract just the labels as_factor(x, levels = "labels")#> [1] Good <NA> Good <NA> Bad Good Good Good <NA> <NA> #> Levels: Bad Good# Or just the values as_factor(x, levels = "values")#> [1] 5 <NA> 5 <NA> 1 5 5 5 <NA> <NA> #> Levels: 1 5# Or combine value and label as_factor(x, levels = "both")#> [1] [5] Good 4 [5] Good 4 [1] Bad [5] Good [5] Good [5] Good #> [9] 2 3 #> Levels: [1] Bad 2 3 4 [5] Good