Skip to content

Commit be17435

Browse files
committed
reversing factors
1 parent a228cea commit be17435

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

DESCRIPTION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Description: Easily automate the following tasks to describe data frames:
77
To do so, the package relies on 'rmarkdown' partials, so you can generate HTML, PDF, and Word documents. Codebooks
88
are also available as tables (CSV, Excel, etc.).
99
The metadata and codebooks are also available at your fingertips via RStudio Addins.
10-
Version: 0.6.3
10+
Version: 0.6.3.9000
1111
Authors@R: person("Ruben", "Arslan", email = "[email protected]", role = c("aut", "cre"))
1212
Depends: R (>= 3.0.1)
1313
URL: https://github.com/rubenarslan/codebook

R/correct_attributes.R

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,12 @@ reverse_labelled_values <- function(x) {
325325
labels <- attributes(x)$labels
326326
values <- unname(labels)
327327
labels <- names(labels)
328+
if (is.factor(x) && is.null(labels) && !is.null(attributes(x)$levels)) {
329+
warning("Turning a factor into a labelled numeric vector")
330+
values <- seq_len(length(attributes(x)$levels))
331+
labels <- attributes(x)$levels
332+
x <- as.numeric(x)
333+
}
328334
if (
329335
sum(!is.na(values)) == 0 ||
330336
(any(x > max(values, na.rm = TRUE) |
@@ -354,7 +360,7 @@ reverse_labelled_values <- function(x) {
354360
recode_replies <- stats::setNames(
355361
as.list(possible_replies), rev(possible_replies))
356362
new_x <- dplyr::recode(as.numeric(x), rlang::UQS(recode_replies))
357-
# cbind(new_x,x)
363+
358364
attributes(new_x) <- attributes(x)
359365
attributes(new_x)$labels <- stats::setNames(rev(values), labels)
360366
new_x

tests/testthat/test_correct_attributes.R

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,4 +260,12 @@ test_that("reverse labelled values", {
260260
expect_equal(reversed[[1]], 3)
261261
expect_equal(reversed[[4]], 2)
262262
expect_equal(reversed[[9]], 1)
263+
264+
x <- factor(rep(1:3, each = 3), levels = 1:5, labels = letters[1:5])
265+
expect_warning(reversed <- reverse_labelled_values(x), "factor")
266+
expect_identical(names(attributes(reversed)$labels), letters[1:5])
267+
expect_equivalent(attributes(reversed)$labels, 5:1)
268+
expect_equal(reversed[[1]], 5)
269+
expect_equal(reversed[[4]], 4)
270+
expect_equal(reversed[[9]], 3)
263271
})

0 commit comments

Comments
 (0)