diff --git a/NEWS.md b/NEWS.md index 66700e9..850f81c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,7 @@ +# REDCapCAST 25.2.1 + +* FIX: `as_factor()` now interprets empty variables with empty levels attribute as logicals to avoid returning factors with empty levels. + # REDCapCAST 25.1.1 The newly introduced extension of `forcats::fct_drop()` has been corrected to work as intended as a method. diff --git a/R/as_factor.R b/R/as_factor.R index 27e424a..b60ab3e 100644 --- a/R/as_factor.R +++ b/R/as_factor.R @@ -7,6 +7,8 @@ #' Please refer to parent functions for extended documentation. #' To avoid redundancy calls and errors, functions are copy-pasted here #' +#' Empty variables with empty levels attribute are interpreted as logicals +#' #' @param x Object to coerce to a factor. #' @param ... Other arguments passed down to method. #' @param only_labelled Only apply to labelled columns? @@ -24,7 +26,14 @@ #' labels = c(Unknown = 9, Refused = 10), #' class = "haven_labelled" #' ) |> -#' as_factor() +#' as_factor() |> class() +#' structure(rep(NA,10), +#' class = c("labelled") +#' ) |> +#' as_factor() |> summary() +#' +#' rep(NA,10) |> as_factor() +#' #' @importFrom forcats as_factor #' @export #' @name as_factor @@ -46,8 +55,6 @@ as_factor.logical <- function(x, ...) { set_attr(x, labels, overwrite = FALSE) } - - #' @rdname as_factor #' @export as_factor.numeric <- function(x, ...) { @@ -121,7 +128,13 @@ as_factor.haven_labelled <- function(x, levels = c("default", "labels", "values" x <- structure(x, label = label) - set_attr(x, labels_all, overwrite = FALSE) + out <- set_attr(x, labels_all, overwrite = FALSE) + + if (all_na(out) & length(levels(out))==0){ + as_factor.logical(out) + } else { + out + } } #' @export diff --git a/man/as_factor.Rd b/man/as_factor.Rd index 4e7c2a4..8ed1012 100644 --- a/man/as_factor.Rd +++ b/man/as_factor.Rd @@ -63,6 +63,8 @@ ta loss in case of rich formatted and labelled data. \details{ Please refer to parent functions for extended documentation. To avoid redundancy calls and errors, functions are copy-pasted here + +Empty variables with empty levels attribute are interpreted as logicals } \examples{ # will preserve all attributes @@ -77,5 +79,12 @@ structure(c(1, 2, 3, 2, 10, 9), labels = c(Unknown = 9, Refused = 10), class = "haven_labelled" ) |> - as_factor() + as_factor() |> class() +structure(rep(NA,10), + class = c("labelled") +) |> + as_factor() |> summary() + +rep(NA,10) |> as_factor() + }