dwww Home | Show directory contents | Find package

test_that("n_distinct gives the correct results on iris", {
  expect_equal(
    sapply(iris, n_distinct),
    sapply(iris, function(.) length(unique(.)))
  )
})

df_var <- data.frame(
  l = c(T, F, F),
  i = c(1, 1, 2),
  d = Sys.Date() + c(1, 1, 2),
  f = factor(letters[c(1, 1, 2)]),
  n = c(1, 1, 2) + 0.5,
  t = Sys.time() + c(1, 1, 2),
  c = letters[c(1, 1, 2)],
  stringsAsFactors = FALSE
)
test_that("n_distinct gives correct results for key types", {
  expect_equal(
    sapply(df_var, n_distinct),
    sapply(df_var, function(.) length(unique(.)))
  )
})

test_that("n_distinct treats NA correctly in the REALSXP case (#384)", {
  expect_equal(n_distinct(c(1.0, NA, NA)), 2)
})

test_that("n_distinct recycles length 1 vectors (#3685)", {
  expect_equal(n_distinct(1, 1:4), 4)
  expect_equal(n_distinct(1:4, 1), 4)

  d <- tibble(x = 1:4)
  res <- d %>%
    summarise(y = sum(x), n1 = n_distinct(y, x), n2 = n_distinct(x, y), n3 = n_distinct(y), n4 = n_distinct(identity(y)), n5 = n_distinct(x))
  expect_equal(res$n1, 4)
  expect_equal(res$n2, 4)
  expect_equal(res$n3, 1)
  expect_equal(res$n4, 1)
  expect_equal(res$n5, 4)

  res <- tibble(g = c(1,1,1,1,2,2), x = c(1,2,3,1,1,2)) %>%
    group_by(g) %>%
    summarise(y = sum(x), n1 = n_distinct(y, x), n2 = n_distinct(x, y), n3 = n_distinct(y), n4 = n_distinct(identity(y)), n5 = n_distinct(x))
  expect_equal(res$n1, c(3,2))
  expect_equal(res$n2, c(3,2))
  expect_equal(res$n3, c(1,1))
  expect_equal(res$n4, c(1,1))
  expect_equal(res$n5, c(3,2))
})

test_that("n_distinct() handles unnamed (#5069)", {
  x <- iris$Sepal.Length
  y <- iris$Sepal.Width
  expect_equal(
    n_distinct(iris$Sepal.Length, iris$Sepal.Width),
    n_distinct(x, y)
  )
})

test_that("n_distinct handles expressions in na.rm (#3686)", {
  d <- tibble(x = c(1:4,NA))
  yes <- TRUE
  no <- FALSE
  expect_equal(d %>% summarise(n = n_distinct(x, na.rm = T)) %>% pull(), 4)
  expect_equal(d %>% summarise(n = n_distinct(x, na.rm = F)) %>% pull(), 5)

  expect_equal(d %>% summarise(n = n_distinct(x, na.rm = yes)) %>% pull(), 4)
  expect_equal(d %>% summarise(n = n_distinct(x, na.rm = no)) %>% pull(), 5)

  expect_equal(d %>% summarise(n = n_distinct(x, na.rm = TRUE || TRUE)) %>% pull(), 4)
})

test_that("n_distinct() respects .data (#5008)", {
  expect_identical(
    data.frame(x = 42) %>% summarise(n = n_distinct(.data$x)),
    data.frame(n = 1L)
  )
})

test_that("n_distinct() works with `{{ }}` (#5461)", {
  wrapper <- function(data, col) {
    summarise(data, result = n_distinct({{ col }}, na.rm = TRUE))
  }

  df <- data.frame(x = c(1, 1, 3, NA))

  expect_identical(
    wrapper(df, x),
    data.frame(result = 2L)
  )
})

Generated by dwww version 1.15 on Sun Jun 16 16:13:34 CEST 2024.