Skip to content
Browse files

Fix bug in id_var when factor levels missing

  • Loading branch information...
1 parent 5bb0da4 commit fb699e417bfc9349e87abb4dac8b057c85b71cc8 @hadley committed Nov 27, 2013
Showing with 8 additions and 1 deletion.
  1. +3 −1 R/id.r
  2. +5 −0 inst/tests/test-ninteraction.r
View
4 R/id.r
@@ -37,6 +37,7 @@ id <- function(.variables, drop = FALSE) {
# Calculate dimensions
ndistinct <- vapply(ids, attr, "n", FUN.VALUE = numeric(1),
USE.NAMES = FALSE)
+
n <- prod(ndistinct)
if (n > 2 ^ 31) {
# Too big for integers, have to use strings, which will be much slower :(
@@ -67,7 +68,8 @@ id_var <- function(x, drop = FALSE) {
if (!is.null(attr(x, "n")) && !drop) return(x)
if (is.factor(x) && !drop) {
- id <- as.integer(addNA(x, ifany = TRUE))
+ x <- addNA(x, ifany = TRUE)
+ id <- as.integer(x)
n <- length(levels(x))
} else {
levels <- sort(unique(x), na.last = TRUE)
View
5 inst/tests/test-ninteraction.r
@@ -55,6 +55,11 @@ test_that("NAs are placed last", {
expect_that(id_var(c(NA, 1)), is_equivalent_to(c(2, 1)))
})
+test_that("factor with missing levels has correct count", {
+ id <- id_var(factor(1, NA))
+ expect_equal(attr(id, "n"), 1)
+})
+
test_that("zero length input gives single number", {
expect_that(id(character()), is_equivalent_to(integer()))
})

0 comments on commit fb699e4

Please sign in to comment.
Something went wrong with that request. Please try again.