1test_that("pillar methods are available for units objects", { 2 skip_if_not_installed("pillar") 3 4 x = set_units(1:3, km) 5 m = c(x, set_units(4:6, g), allow_mixed = TRUE) 6 7 expect_equal(unclass(pillar::type_sum(x)), "[km]") 8 expect_s3_class(pillar::type_sum(x), "type_sum_units") 9 expect_equal(pillar::type_sum(m), "mixed_units") 10 11 expect_snapshot({ 12 pillar::pillar(x[1]) 13 pillar::pillar(m[1]) 14 }) 15}) 16 17skip_if_not_installed("vctrs", "0.3.1") 18skip_if_not_installed("dplyr", "1.0.0") 19 20test_that("units have coercion methods", { 21 x = set_units(1:3, "cm") 22 y = set_units(4.0, "m") 23 z = set_units(10, "celsius") 24 25 expect_error(vctrs::vec_ptype_common(y, x, z), class = "vctrs_error_incompatible_type") 26 expect_error(vctrs::vec_cast_common(y, x, z), class = "vctrs_error_incompatible_type") 27 28 expect_identical(vctrs::vec_ptype_common(x, y, x), set_units(double(), "cm")) 29 expect_identical(vctrs::vec_ptype_common(x, x), set_units(integer(), "cm")) 30 expect_identical(vctrs::vec_ptype_common(y, x, x), set_units(double(), "m")) 31 32 expect_identical( 33 vctrs::vec_cast_common(x, y), 34 list(set_units(c(1, 2, 3), "cm"), set_units(400, "cm")) 35 ) 36 expect_identical( 37 vctrs::vec_cast_common(y, x), 38 list(set_units(4, "m"), set_units(c(0.01, 0.02, 0.03), "m")) 39 ) 40 41 # Casting to integer with fractional cm is lossy 42 expect_error( 43 vctrs::vec_cast_common(y, x, .to = set_units(0L, "m")), 44 class = "vctrs_error_cast_lossy" 45 ) 46}) 47 48test_that("can combine units vectors", { 49 x <- set_units(1:3, "cm") 50 y <- set_units(4, "m") 51 52 exp = set_units(c(1, 2, 3, 400), "cm") 53 expect_identical(vctrs::vec_c(x, y), exp) 54 55 # Recursive case 56 df1 = dplyr::tibble(x = dplyr::tibble(x = x)) 57 df2 = dplyr::tibble(x = dplyr::tibble(x = y)) 58 df_exp = dplyr::tibble(x = dplyr::tibble(x = exp)) 59 expect_identical(vctrs::vec_c(df1, df2), df_exp) 60}) 61 62test_that("can slice units vectors", { 63 x = set_units(1:3, "cm") 64 exp = list(set_units(1L, "cm"), set_units(2L, "cm"), set_units(3L, "cm")) 65 expect_identical(vctrs::vec_chop(x), exp) 66 67 # Recursive case 68 df = dplyr::tibble(dplyr::tibble(x = x)) 69 exp = list( 70 dplyr::tibble(x = set_units(1L, "cm")), 71 dplyr::tibble(x = set_units(2L, "cm")), 72 dplyr::tibble(x = set_units(3L, "cm")) 73 ) 74 expect_identical(vctrs::vec_chop(df), exp) 75}) 76 77`%>%` <- dplyr::`%>%` 78 79test_that("split-apply-combine with dplyr and base agree", { 80 iris2 <- iris 81 for (i in 1:4) 82 units(iris2[,i]) <- "cm" 83 84 out <- iris2 %>% 85 dplyr::group_by(Species) %>% 86 dplyr::summarise(dplyr::across(where(is.numeric), mean)) 87 88 # Transform to list of lists 89 out <- vctrs::vec_chop(out[2:5]) %>% 90 stats::setNames(out$Species) %>% 91 lapply(as.list) 92 93 exp <- lapply(split(iris2[1:4], iris2$Species), lapply, mean) 94 expect_equal(out, exp) 95}) 96