Debian Codegraph @

tests/testthat/test-rect.dendrogram.R

raw
1 # library(testthat)
2 # library(dendextend)
3
4
5 context("rect.dendrogram")
6
7
8 test_that("rect.dendrogram works", {
9
10 hc <- USArrests[1:10, ] %>%
11 dist() %>%
12 hclust()
13 dend <- as.dendrogram(hc)
14
15 # standard
16 plot(dend)
17 rect.dendrogram(dend, k = 4, which = 3)
18 rect.dendrogram(dend, k = 4, x = 4)
19 rect.dendrogram(dend, h = 70, x = 1)
20
21 # horizontal
22 plot(dend, horiz = T)
23 rect.dendrogram(dend, k = 4, which = 3, horiz = T, text = "test")
24
25 # if non-denrogram object passed in
26 expect_error(
27 rect.dendrogram(hc, k = 4)
28 )
29 # if more than one k value passed in
30 expect_error(
31 rect.dendrogram(dend, k = c(2,3))
32 )
33 # if both k and h specified
34 expect_error(
35 rect.dendrogram(dend, k = 2, h = 2)
36 )
37 # if neither k nor h are specified
38 expect_error(
39 rect.dendrogram(dend)
40 )
41 # if k == 1
42 expect_error(
43 rect.dendrogram(dend, k = 1, stop_if_out = T)
44 )
45 expect_warning(
46 rect.dendrogram(dend, k = 1)
47 )
48 # if both x and which are specified
49 expect_error(
50 rect.dendrogram(dend, k = 4, x = 2, which = 3)
51 )
52 # if which > k
53 expect_error(
54 rect.dendrogram(dend, k = 4, which = 5)
55 )
56 # if k >= number of leaves
57 expect_warning(
58 rect.dendrogram(dend, k = 10)
59 )
60
61 })
62
63
64 test_that("identify.dendrogram works", {
65
66 hc <- USArrests[1:10, ] %>%
67 dist() %>%
68 hclust()
69 dend <- as.dendrogram(hc)
70
71 # replace locator function with one that automatically clicks to make test non-interactive
72 locator_counter <<- 0
73 with_mocked_bindings(
74 {
75 plot(dend, horiz = TRUE)
76 vec <- identify(dend, horiz = TRUE, FUN = function(x) x + 1, DEV.FUN = 2)
77 },
78 locator = function(x) {
79 locator_counter <<- locator_counter + 1
80 if (locator_counter == 1) return(list(x = 172, y = 5))
81 if (locator_counter == 2) return(list(x = 172, y = 1))
82 return(NULL)
83 }
84 )
85 expect_identical(
86 vec[[2]], c("Connecticut" = 8)
87 )
88 expect_true(
89 all(vec[[1]] == c(2:7, 9:11))
90 )
91
92 })