Skip to content

Commit

Permalink
spread() works fine when the id variable has names.
Browse files Browse the repository at this point in the history
  • Loading branch information
romainfrancois committed Feb 5, 2019
1 parent d5c0acc commit 08e124c
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 2 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

* `crossing()` preserves factor levels (#410).

* `spread()` works when the id variable has names (#525).

# tidyr 0.8.2

* `separate()` now accepts `NA` as a column name in the `into` argument to
Expand Down
2 changes: 1 addition & 1 deletion R/id.R
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ id <- function(.variables, drop = FALSE) {
}

id_var <- function(x, drop = FALSE) {
if (!is_null(attr(x, "n")) && !drop) return(x)
if (!is_null(attr(x, "n", exact = TRUE)) && !drop) return(x)

if (is.factor(x) && !drop) {
x_na <- addNA(x, ifany = TRUE)
Expand Down
7 changes: 6 additions & 1 deletion tests/testthat/test-id.R
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
context("id")

test_that("drop preserves count of factor levels", {
x <- factor(, levels = c("a", "b"))
x <- factor(levels = c("a", "b"))
expect_equal(id_var(x), structure(integer(), n = 2))
expect_equal(id(data.frame(x)), structure(integer(), n = 2))
})
Expand All @@ -10,3 +10,8 @@ test_that("id works with dimensions beyond integer range", {
df <- data.frame(matrix(c(1, 2), nrow = 2, ncol = 32))
expect_equal(id(df), structure(c(1, 2), n = 2 ^ 32))
})

test_that("id_var() handles named vectors (#525)", {
res <- id_var(c(a = 5, b = 3, c = 5))
expect_equal(res, structure(c(2L, 1L, 2L), n = 2L))
})
11 changes: 11 additions & 0 deletions tests/testthat/test-spread.R
Original file line number Diff line number Diff line change
Expand Up @@ -278,3 +278,14 @@ test_that("ulevels returns unique elements of a list for a list input", {
test_list <- list(a = 1:6, b = 1:6)
expect_equal(ulevels(test_list), unique(test_list))
})

test_that("spread works when id column has names (#525)", {
df <- tibble(
key = factor(c("a", "b", "c"), levels = letters[1:5]),
out = 1:3,
id = c(a = 1, b = 2, c = 3)
)
res <- spread(df, key, out, drop = FALSE)
expect_equal(names(res), c("id", letters[1:5]))
})

0 comments on commit 08e124c

Please sign in to comment.