/tests/testthat/test-dt_pivot_wider.R

https://github.com/TysonStanley/tidyfast · R · 73 lines · 53 code · 17 blank · 3 comment · 0 complexity · 3a0886489fa562806634dfff71fea692 MD5 · raw file

  1. # tests from tidyr regarding pivot_wider
  2. test_that("can pivot all cols to wide", {
  3. df <- data.table(label = c("x", "y", "z"), val = 1:3)
  4. pivot_df <- dt_pivot_wider(df, names_from = label, values_from = val)
  5. expect_named(pivot_df, c("x", "y", "z"))
  6. expect_equal(nrow(pivot_df), 1)
  7. })
  8. test_that("non-pivoted cols are preserved", {
  9. df <- data.table(a = 1, label = c("x", "y"), val = 1:2)
  10. pivot_df <- dt_pivot_wider(df, names_from = label, values_from = val)
  11. expect_named(pivot_df, c("a", "x", "y"))
  12. expect_equal(nrow(pivot_df), 1)
  13. })
  14. test_that("implicit missings turn into explicit missings", {
  15. df <- data.table(a = 1:2, label = c("x", "y"), val = 1:2)
  16. pivot_df <- dt_pivot_wider(df, names_from = label, values_from = val)
  17. expect_equal(pivot_df$a, c(1, 2))
  18. expect_equal(pivot_df$x, c(1, NA))
  19. expect_equal(pivot_df$y, c(NA, 2))
  20. })
  21. test_that("can override default keys", {
  22. df <- dplyr::tribble(
  23. ~row, ~name, ~var, ~value,
  24. 1, "Sam", "age", 10,
  25. 2, "Sam", "height", 1.5,
  26. 3, "Bob", "age", 20,
  27. )
  28. pv <- dt_pivot_wider(df, id_cols = name, names_from = var, values_from = value)
  29. expect_equal(nrow(pv), 2)
  30. })
  31. # multiple values ----------------------------------------------------------
  32. test_that("can pivot from multiple measure cols", {
  33. df <- data.table(row = 1, var = c("x", "y"), a = 1:2, b = 3:4)
  34. pv <- dt_pivot_wider(df, names_from = var, values_from = c(a, b))
  35. expect_named(pv, c("row", "a_x", "a_y", "b_x", "b_y"))
  36. expect_equal(pv$a_x, 1)
  37. expect_equal(pv$b_y, 4)
  38. })
  39. test_that("can pivot from multiple measure cols using all keys", {
  40. df <- data.table(var = c("x", "y"), a = 1:2, b = 3:4)
  41. pv <- dt_pivot_wider(df, names_from = var, values_from = c(a, b))
  42. expect_named(pv, c("a_x", "a_y", "b_x", "b_y"))
  43. expect_equal(pv$a_x, 1)
  44. expect_equal(pv$b_y, 4)
  45. })
  46. # select helpers ----------------------------------------------------------
  47. test_that("can pivot from multiple measure cols using helpers", {
  48. df <- data.table(row = 1, var = c("x", "y"), a = 1:2, b = 3:4)
  49. pv <- dt_pivot_wider(df,
  50. names_from = var,
  51. values_from = c(dt_starts_with("a"), dt_ends_with("b"))
  52. )
  53. expect_named(pv, c("row", "a_x", "a_y", "b_x", "b_y"))
  54. expect_equal(pv$a_x, 1)
  55. expect_equal(pv$b_y, 4)
  56. })