make_factor() converts a labelled numeric, factor, or character vector to
an R factor. For labelled numeric input (e.g., from
haven or with a "labels" attribute), factor levels are derived from
the value labels. For factor input, levels are preserved. For character
input, levels are set alphabetically.
When called inside mutate(), metadata is recorded in
@metadata@transformations[[col]].
Usage
make_factor(
x,
ordered = FALSE,
drop_levels = TRUE,
force = FALSE,
na.rm = FALSE,
.label = NULL,
.description = NULL
)Arguments
- x
Vector to convert. Must be a labelled numeric, plain numeric with a
"labels"attribute, R factor, or character vector.- ordered
logical(1). IfTRUE, returns an ordered factor.- drop_levels
logical(1). IfTRUE(the default), removes levels with no observed values inx.- force
logical(1). IfTRUE, coerce a numericxwithout value labels viaas.factor(), issuing asurveytidy_warning_make_factor_forcedwarning. IfFALSE(the default), error instead.- na.rm
logical(1). IfTRUE, values inattr(x, "na_values")andattr(x, "na_range")are converted toNAbefore building factor levels, so they do not produce factor levels. Ignored for factor and character input.- .label
character(1)orNULL. Variable label override. IfNULL, inherits fromattr(x, "label"); if that is alsoNULL, falls back to the column name.- .description
character(1)orNULL. Transformation description stored insurveytidy_recode.
See also
Other transformation:
make_binary(),
make_dicho(),
make_flip(),
make_rev()
Examples
library(dplyr)
d <- surveycore::as_survey(
data.frame(x = c(1, 2, 1, 2), wt = c(1, 1, 1, 1)),
weights = wt
)
#> Warning: ! No `ids` or `strata` specified.
#> ℹ Creating a <survey_srs> design (equal-probability SRS).
#> ✔ Use `as_survey_srs()` to create SRS designs without this warning.
x <- c(1, 2, 1, 2)
attr(x, "labels") <- c("Yes" = 1, "No" = 2)
make_factor(x)
#> 1 2 1 2
#> Yes No Yes No
#> attr(,"label")
#> [1] x
#> attr(,"surveytidy_recode")
#> attr(,"surveytidy_recode")$fn
#> [1] make_factor
#>
#> attr(,"surveytidy_recode")$var
#> [1] x
#>
#> attr(,"surveytidy_recode")$description
#> NULL
#>
#> Levels: Yes No
