tests/testthat/test-generate-controls.R

context("generate() controls")

# setup ----
set.seed(1)
eg_df <- data.frame(
  id = as.character(1:100),
  a = rnorm(100),
  b = rnorm(100),
  c = rnorm(100),
  d = factor(sample(c("a", "b", "c"), 100, replace=TRUE)),
  e = sample(1:5, 100, replace=TRUE),
  f = sample(c("zzzz", "zzza", "zzaa", "zaaa", "aaaa", "zzzzz"), 100, replace = TRUE),
  g = sample(c("yyyy", "yyya", "yyaa", "yaaa", "aaaa", "yyyyy"), 100, replace = TRUE)
)

# controls errors ----
testthat::test_that("controls errors", {
  # test that an informative error is given if something other than a dataframe is passed
  testthat::expect_error(
    control_for("uh oh!", d),
    regexp = "Expected df to be of class data frame, not character",
    fixed = TRUE
  )
  testthat::expect_error(
    control_for_map("uh oh!", function() {}, d),
    regexp = "Expected df to be of class data frame, not character",
    fixed = TRUE
  )
  #() error from as.LexOPS_pipeline() for control_for_euc() is different, because of different order of operations)
  testthat::expect_error(
    control_for_euc("uh oh!", c(a, b), -10:10),
    regexp = "Expected data.frame object",
    fixed = TRUE
  )
  # check that an informative error is given if a tolerance is included for a non-numeric variable
  testthat::expect_error(
    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for(d, "a"),
    regexp = "Non-numeric variables should not have tolerances; they are always matched exactly",
    fixed = TRUE
  )
  # check that an informative error is given if a NUMERIC tolerance is included for a non-numeric variable
  testthat::expect_error(
    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for(d, -2:2),
    regexp = "Non-numeric variables should not have tolerances; they are always matched exactly",
    fixed = TRUE
  )
  # check that an informative error is given if the variable is missing
  testthat::expect_error(
    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for(missing_var),
    regexp = "Unknown column: 'missing_var'",
    fixed = TRUE
  )
  # check that an informative error is given if the user tries to use split_by() syntax in control_for()
  testthat::expect_error(
    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for(b, -1:1 ~ -5:5),
    regexp = "control_for() expects only one tolerance, not 2: check there are no tildes (~)",
    fixed = TRUE
  )
})

# control_for_map() errors
testthat::test_that("control maps errors", {
  # if the function returns the wrong number of outputs, will get an informative error
  testthat::expect_error(
    {
      library(stringdist)

      stringdist2 <- function(...) {
        out <- stringdist(...)
        out[1:(length(out)-1)]
      }

      eg_df |>
        set_options(id_col = "id") |>
        split_by(a, -5:-0.1 ~ 0.1:5) |>
        control_for_map(stringdist2, f, 0:2, method="lv") |>
        generate(36, silent=TRUE)
    },
    regexp = "control function '.+' returned length \\d+ but expected 1 or \\d+"
  )
  # check that an informative error is given if the variable is missing
  testthat::expect_error(
    {
      library(stringdist)

      eg_df |>
        set_options(id_col = "id") |>
        split_by(a, -5:-0.1 ~ 0.1:5) |>
        control_for_map(stringdist, missing_var, 0:2, method="lv")
    },
    regexp = "Unknown column: 'missing_var'",
    fixed = TRUE
  )
  # check that an informative error is given if the user tries to use split_by() syntax in control_for_map()
  testthat::expect_error(
    {
      library(stringdist)

      eg_df |>
        set_options(id_col = "id") |>
        split_by(a, -5:-0.1 ~ 0.1:5) |>
        control_for_map(stringdist, f, 0:2 ~ 4:6, method="lv")
    },
    regexp = "control_for_map() expects only one tolerance: check there are no tildes (~)",
    fixed = TRUE
  )
  # informative error is given if the user tries to pass a non-function object as the fun argument
  testthat::expect_error(
    {
      eg_df |>
        set_options(id_col = "id") |>
        split_by(a, -5:-0.1 ~ 0.1:5) |>
        control_for_map("uh oh!", f, 0:2)
    },
    regexp = "Argument `fun` should be an object of class, 'function'",
    fixed = TRUE
  )
})

# controls ----
testthat::test_that("controls", {
  # test that categorical controls are applied correctly
  testthat::expect_equal(
    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for(d) |>
      generate(20, silent=TRUE) |>
      tidyr::pivot_longer(c(A1, A2), names_to = "condition", values_to = "id") |>
      dplyr::left_join(eg_df, by = "id") |>
      dplyr::group_by(item_nr) |>
      dplyr::filter(length(unique(d)) == 1) |>
      dplyr::ungroup() |>
      nrow(),
    40  # as pivot_longer but no group_by(item_nr)
  )
  # test that exact numeric controls are applied correctly
  testthat::expect_equal(
    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for(e, 0:0) |>
      generate(20, silent=TRUE) |>
      tidyr::pivot_longer(c(A1, A2), names_to = "condition", values_to = "id") |>
      dplyr::left_join(eg_df, by = "id") |>
      dplyr::group_by(item_nr) |>
      dplyr::filter(length(unique(e)) == 1) |>
      dplyr::ungroup() |>
      nrow(),
    40  # as pivot_longer but no group_by(item_nr)
  )
  # test that inexact integer numeric controls are applied correctly
  testthat::expect_equal(
    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for(e, -1:1) |>
      generate(20, silent=TRUE) |>
      tidyr::pivot_longer(c(A1, A2), names_to = "condition", values_to = "id") |>
      dplyr::left_join(eg_df, by = "id") |>
      dplyr::group_by(item_nr) |>
      dplyr::summarise(max_diff = max(e) - min(e)) |>
      dplyr::filter(dplyr::between(max_diff, -1, 1)) |>
      dplyr::ungroup() |>
      nrow(),
    20
  )
  # test that inexact float numeric controls are applied correctly
  testthat::expect_equal(
    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for(b, -0.25:0.25) |>
      generate(20, silent=TRUE) |>
      tidyr::pivot_longer(c(A1, A2), names_to = "condition", values_to = "id") |>
      dplyr::left_join(eg_df, by = "id") |>
      dplyr::group_by(item_nr) |>
      dplyr::summarise(max_diff = max(b) - min(b)) |>
      dplyr::filter(dplyr::between(max_diff, -0.25, 0.25)) |>
      dplyr::ungroup() |>
      nrow(),
    20
  )
  # test that inexact, assymmetric float numeric controls are applied correctly
  testthat::expect_equal(
    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for(b, -0.37:0.1) |>
      generate(30, silent=TRUE) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, b) |>
          dplyr::rename(A1_b = b),
        by = c("A1" = "id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, b) |>
          dplyr::rename(A2_b = b),
        by = c("A2" = "id")
      ) |>
      dplyr::mutate(b_diff = ifelse(match_null == "A1", A2_b - A1_b, A1_b - A2_b)) |>
      dplyr::filter(dplyr::between(b_diff, -0.37, 0.1)) |>
      nrow(),
    30
  )
})

# match_null options ----
testthat::test_that("match_null options", {
  # check balanced match nulls exist in equal frequencies for n divisible by number of conds
  testthat::expect_true({
    match_null_counts <- eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for(d) |>
      generate(32, match_null = "balanced", silent=TRUE) |>
      dplyr::group_by(match_null) |>
      dplyr::count() |>
      dplyr::pull(n)
    all(match_null_counts == 16)
  })
  # check balanced match nulls exist in almost equal frequencies for n not divisible by number of conds
  testthat::expect_true({
    match_null_counts <- eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for(d) |>
      generate(33, match_null = "balanced", silent=TRUE) |>
      dplyr::group_by(match_null) |>
      dplyr::count() |>
      dplyr::pull(n)
    all(sort(match_null_counts) == c(16, 17))
  })
  # check "first" match nulls work
  testthat::expect_true({
    match_nulls <- eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      split_by(e, 0:3 ~ 4:6) |>
      control_for(d) |>
      generate(12, match_null = "first", silent=TRUE) |>
      dplyr::pull(match_null)
    all(match_nulls == "A1_B1")
  })
  # check specific match nulls can be selected
  testthat::expect_true({
    match_nulls <- eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      split_by(e, 0:3 ~ 4:6) |>
      control_for(d) |>
      generate(12, match_null = "A1_B2", silent=TRUE) |>
      dplyr::pull(match_null)
    all(match_nulls == "A1_B2")
  })
  # check inclusive match nulls work
  testthat::expect_equal(
    eg_df |>
      set_options(id_col = "id") |>
      split_by(d, "a" ~ "b" ~ "c") |>
      control_for(b, -1.5:10) |>
      generate(5, match_null = "inclusive", silent=TRUE) |>
      long_format() |>
      dplyr::group_by(item_nr) |>
      dplyr::filter(
        # note that assymmetric tolerances are cut short to become symmmetrical, with a maximum extent of the shortest distance from zero of the supplied positive and negative tolernces. As a result, -1.5:10 becomes -1.5:1.5
        max(b) - min(b) <= 1.5
      ) |>
      nrow(),
    15
  )
})

# control_for_map ----
testthat::test_that("control_for_map", {
  # test with two conditions
  testthat::expect_equal({
    library(stringdist)
    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for_map(stringdist, f, 0:2, method="lv") |>
      generate(36, silent=TRUE) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A1_f = f),
        by = c("A1" = "id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A2_f = f),
        by = c("A2" = "id")
      ) |>
      dplyr::rowwise() |>
      dplyr::mutate(ld = stringdist(A1_f, A2_f, method="lv")) |>
      dplyr::filter(ld <= 2) |>
      nrow()
  }, 36)
  # test that the returned value matches that calculate manually
  testthat::expect_equal({
    library(stringdist)
    wide_res <- eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for_map(stringdist, f, 0:2, method="lv", name="gen_ld") |>
      generate(36, silent=TRUE)

    wide_res |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A1_f = f),
        by = c("A1" = "id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A2_f = f),
        by = c("A2" = "id")
      ) |>
      dplyr::rowwise() |>
      dplyr::mutate(ld = stringdist(A1_f, A2_f, method="lv")) |>
      dplyr::right_join(long_format(wide_res), by=c("item_nr", "match_null")) |>
      # each row either has the expected distance, or else a distance of 0 from itself
      dplyr::filter(ld == gen_ld | gen_ld == 0) |>
      nrow()
  }, 72)
  # test with a non-numeric function output
  testthat::expect_equal({
    library(stringdist)

    stringdist_okay <- function(target, matches) {
      dist <- stringdist(target, matches, method="lv")
      ifelse(dist <= 2, "okay", "not_okay")
    }

    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for_map(stringdist_okay, f, "okay") |>
      generate(36, silent=TRUE) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A1_f = f),
        by = c("A1" = "id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A2_f = f),
        by = c("A2" = "id")
      ) |>
      dplyr::rowwise() |>
      dplyr::mutate(ld = stringdist(A1_f, A2_f, method="lv")) |>
      dplyr::filter(ld <= 2) |>
      nrow()
  }, 36)
  # test with three conditions and not including 0 in tolerance
  testthat::expect_equal({
    library(stringdist)
    eg_df |>
      set_options(id_col = "id") |>
      split_by(d, "a" ~ "b" ~ "c") |>
      control_for_map(stringdist, f, 1:4, method="lv") |>
      generate(23, silent=TRUE) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A1_f = f),
        by = c("A1" = "id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A2_f = f),
        by = c("A2" = "id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A3_f = f),
        by = c("A3" = "id")
      ) |>
      dplyr::mutate(match_null_f = dplyr::case_when(
        match_null == "A1" ~ A1_f,
        match_null == "A2" ~ A2_f,
        match_null == "A3" ~ A3_f
      )) |>
      tidyr::pivot_longer(c(A1_f, A2_f, A3_f), names_to = "condition", values_to = "f") |>
      dplyr::rowwise() |>
      dplyr::mutate(ld = stringdist(match_null_f, f, method="lv")) |>
      dplyr::filter(ld >= 1 & ld <= 4) |>
      nrow()
    },
  46  # (n_items * n_cells) - n_items; as each of the 2 conditions will be within the tolerance to each other, and the match null will be an exact match with itself
  )
  # test with three conditions and inclusive matching
  testthat::expect_equal({
    library(stringdist)
    wide_res <- eg_df |>
      set_options(id_col = "id") |>
      split_by(d, "a" ~ "b" ~ "c") |>
      control_for_map(stringdist, f, 0:4, method="lv", name="gen_strdist") |>
      generate(23, match_null="inclusive", silent=TRUE)

    max_stringdist <- function(strings, method="lv") {
      max(stringdistmatrix(strings, method=method))
    }

    wide_res |>
      long_format() |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A1_f = f),
        by = c("id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A2_f = f),
        by = c("id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A3_f = f),
        by = c("id")
      ) |>
      dplyr::mutate(cond_f = dplyr::case_when(
        condition == "A1" ~ A1_f,
        condition == "A2" ~ A2_f,
        condition == "A3" ~ A3_f
      )) |>
      dplyr::select(-A1_f, -A2_f, -A3_f) |>
      dplyr::group_by(item_nr) |>
      dplyr::mutate(manual_max_strdist = max_stringdist(cond_f)) |>
      dplyr::ungroup() |>
      dplyr::filter(manual_max_strdist <= 4) |>
      nrow()
  },
  69
  )
  # test that with three conditions and inclusive matching, the resultant column is NA
  testthat::expect_equal({
    library(stringdist)
    wide_res <- eg_df |>
      set_options(id_col = "id") |>
      split_by(d, "a" ~ "b" ~ "c") |>
      control_for_map(stringdist, f, 0:4, method="lv", name="gen_strdist") |>
      generate(23, match_null="inclusive", silent=TRUE)

    max_stringdist <- function(strings, method="lv") {
      max(stringdistmatrix(strings, method=method))
    }

    wide_res |>
      long_format() |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A1_f = f),
        by = c("id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A2_f = f),
        by = c("id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A3_f = f),
        by = c("id")
      ) |>
      dplyr::mutate(cond_f = dplyr::case_when(
        condition == "A1" ~ A1_f,
        condition == "A2" ~ A2_f,
        condition == "A3" ~ A3_f
      )) |>
      dplyr::select(-A1_f, -A2_f, -A3_f) |>
      dplyr::group_by(item_nr) |>
      dplyr::mutate(manual_max_strdist = max_stringdist(cond_f)) |>
      dplyr::ungroup() |>
      dplyr::filter(is.na(gen_strdist)) |>
      nrow()
  },
  69
  )
  # test with multiple control functions
  testthat::expect_equal({
    library(stringdist)
    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for_map(stringdist, f, 2:Inf, method="osa") |>
      control_for_map(stringdist, g, 3:3, method="lv") |>
      generate(29, silent=TRUE) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A1_f = f),
        by = c("A1" = "id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, f) |>
          dplyr::rename(A2_f = f),
        by = c("A2" = "id")
      ) |>
      dplyr::rowwise() |>
      dplyr::mutate(ld_f = stringdist(A1_f, A2_f, method="osa")) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, g) |>
          dplyr::rename(A1_g = g),
        by = c("A1" = "id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::select(id, g) |>
          dplyr::rename(A2_g = g),
        by = c("A2" = "id")
      ) |>
      dplyr::rowwise() |>
      dplyr::mutate(ld_g = stringdist(A1_g, A2_g, method="lv")) |>
      dplyr::filter(ld_g == 3, ld_f >= 2) |>
      nrow()
  }, 29)
  # test passing of arguments via ellipses
  testthat::expect_equal({
    library(stringdist)

    plus_minus_strdist <- function(a, b, method="osa", minus=FALSE) {
      x <- stringdist(a, b, method=method)
      if (minus) x <- 0-x
      x
    }

    eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for_map(plus_minus_strdist, f, -3:0, minus=TRUE) |>
      generate(27, silent=TRUE) |>
      long_format() |>
      dplyr::filter(as.numeric(control_map_1) <= 0 & as.numeric(control_map_1) >= -3) |>
      nrow()
  }, 54)
})

# control_for_euc ----
testthat::test_that("control_for_euc", {
  # test with two conditions, comparing manual euclidean distance calculation to that from control_for_euc()
  testthat::expect_equal({
    wide_res <- eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for_euc(
        c(b, e),
        0:0.75,
        name = "gen_euc_dist"
      ) |>
      generate(20, silent=TRUE)

    manual_euc_dist <- wide_res |>
      dplyr::left_join(
        eg_df |>
          dplyr::filter((a>=-5 & a<=-0.1) | (a>=0.1 & a<=5)) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = as.numeric(scale(b)),
            e = as.numeric(scale(e))
          ) |>
          dplyr::rename(A1_b = b, A1_e = e),
        by = c("A1" = "id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::filter((a>=-5 & a<=-0.1) | (a>=0.1 & a<=5)) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = as.numeric(scale(b)),
            e = as.numeric(scale(e))
          ) |>
          dplyr::rename(A2_b = b, A2_e = e),
        by = c("A2" = "id")
      ) |>
      dplyr::mutate(
        dist_b = A1_b - A2_b,
        dist_e = A1_e - A2_e,
        man_euc_dist = as.numeric(sqrt(dist_b**2 + dist_e**2))
      )

    wide_res |>
      long_format() |>
      dplyr::mutate(gen_euc_dist = as.numeric(gen_euc_dist)) |>
      dplyr::filter(condition != match_null) |>
      dplyr::left_join(
        dplyr::select(manual_euc_dist, item_nr, man_euc_dist),
        by = "item_nr"
      ) |>
      # NB: only one row per pair should have the Euclidean distance, as the other in the pair will be the match null and will have a distance of zero from itself
      dplyr::filter(
        abs(gen_euc_dist - man_euc_dist) <= 1e-12
      ) |>
      nrow()
  }, 20)
  # test inclusive matching with 3 conditions is within the requested tolerance
  testthat::expect_equal({
    wide_res <- eg_df |>
      set_options(id_col = "id") |>
      split_by(d, "a" ~ "b" ~ "c") |>
      control_for_euc(
        c(b, e),
        0:0.75,
        name = "gen_euc_dist"
      ) |>
      generate(20, match_null="inclusive", silent=TRUE)

    manual_euc_dist <- wide_res |>
      # get A1 values
      dplyr::left_join(
        eg_df |>
          dplyr::filter(d %in% c("a", "b", "c")) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = as.numeric(scale(b)),
            e = as.numeric(scale(e))
          ) |>
          dplyr::rename(A1_b = b, A1_e = e),
        by = c("A1" = "id")
      ) |>
      # get A2 values
      dplyr::left_join(
        eg_df |>
          dplyr::filter(d %in% c("a", "b", "c")) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = as.numeric(scale(b)),
            e = as.numeric(scale(e))
          ) |>
          dplyr::rename(A2_b = b, A2_e = e),
        by = c("A2" = "id")
      ) |>
      # get A3 values
      dplyr::left_join(
        eg_df |>
          dplyr::filter(d %in% c("a", "b", "c")) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = as.numeric(scale(b)),
            e = as.numeric(scale(e))
          ) |>
          dplyr::rename(A3_b = b, A3_e = e),
        by = c("A3" = "id")
      ) |>
      dplyr::mutate(
        # distance between A1 and A2
        man_euc_dist_12 = as.numeric(sqrt((A1_b - A2_b)**2 + (A1_e - A2_e)**2)),
        # distance between A1 and A3
        man_euc_dist_13 = as.numeric(sqrt((A1_b - A3_b)**2 + (A1_e - A3_e)**2)),
        # distance between A2 and A3
        man_euc_dist_23 = as.numeric(sqrt((A2_b - A3_b)**2 + (A2_e - A3_e)**2))
      )

    wide_res |>
      long_format() |>
      dplyr::left_join(
        dplyr::select(manual_euc_dist, item_nr, man_euc_dist_12, man_euc_dist_13, man_euc_dist_23),
        by = c("item_nr")
      ) |>
      dplyr::rowwise() |>
      dplyr::mutate(max_man_euc_dist = max(c(
        man_euc_dist_12, man_euc_dist_13, man_euc_dist_23
      ))) |>
      dplyr::ungroup() |>
      dplyr::filter(max_man_euc_dist <= 0.75) |>
      nrow()
  }, 60)
  # test inclusive matching with 3 conditions returns a long-format column that is the maximum of the possible euclidean distances
  testthat::expect_equal({
    wide_res <- eg_df |>
      set_options(id_col = "id") |>
      split_by(d, "a" ~ "b" ~ "c") |>
      control_for_euc(
        c(b, e),
        0:0.75,
        name = "gen_euc_dist"
      ) |>
      generate(20, match_null="inclusive", silent=TRUE)

    manual_euc_dist <- wide_res |>
      # get A1 values
      dplyr::left_join(
        eg_df |>
          dplyr::filter(d %in% c("a", "b", "c")) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = as.numeric(scale(b)),
            e = as.numeric(scale(e))
          ) |>
          dplyr::rename(A1_b = b, A1_e = e),
        by = c("A1" = "id")
      ) |>
      # get A2 values
      dplyr::left_join(
        eg_df |>
          dplyr::filter(d %in% c("a", "b", "c")) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = as.numeric(scale(b)),
            e = as.numeric(scale(e))
          ) |>
          dplyr::rename(A2_b = b, A2_e = e),
        by = c("A2" = "id")
      ) |>
      # get A3 values
      dplyr::left_join(
        eg_df |>
          dplyr::filter(d %in% c("a", "b", "c")) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = as.numeric(scale(b)),
            e = as.numeric(scale(e))
          ) |>
          dplyr::rename(A3_b = b, A3_e = e),
        by = c("A3" = "id")
      ) |>
      dplyr::mutate(
        # distance between A1 and A2
        man_euc_dist_12 = as.numeric(sqrt((A1_b - A2_b)**2 + (A1_e - A2_e)**2)),
        # distance between A1 and A3
        man_euc_dist_13 = as.numeric(sqrt((A1_b - A3_b)**2 + (A1_e - A3_e)**2)),
        # distance between A2 and A3
        man_euc_dist_23 = as.numeric(sqrt((A2_b - A3_b)**2 + (A2_e - A3_e)**2))
      )

    wide_res |>
      long_format() |>
      dplyr::mutate(gen_euc_dist = as.numeric(gen_euc_dist)) |>
      dplyr::left_join(
        dplyr::select(manual_euc_dist, item_nr, man_euc_dist_12, man_euc_dist_13, man_euc_dist_23),
        by = c("item_nr")
      ) |>
      dplyr::rowwise() |>
      dplyr::mutate(max_man_euc_dist = max(c(
        man_euc_dist_12, man_euc_dist_13, man_euc_dist_23
      ))) |>
      dplyr::ungroup() |>
      dplyr::filter(abs(gen_euc_dist - max_man_euc_dist) <= 1e-12) |>
      nrow()
  }, 60)
  # test inclusive matching with 4 factorial cells and 2 splits returns a long-format column that is the maximum of the possible euclidean distances
  testthat::expect_equal({
    wide_res <- eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      split_by(d, "a" ~ "b") |>
      control_for_euc(
        c(b, e),
        0:1.5,
        name = "gen_euc_dist"
      ) |>
      generate(6, match_null="inclusive", silent=TRUE)

    manual_euc_dist <- wide_res |>
      # get A1_B1 values
      dplyr::left_join(
        eg_df |>
          dplyr::filter(
            (a>=-5 & a<=-0.1 & d == "a") |  # A1_B1
            (a>=-5 & a<=-0.1 & d == "b") |  # A1_B2
            (a>=0.1 & a<=5 & d == "a") |  # A2_B1
            (a>=0.1 & a<=5 & d == "b")  # A2_B2
          ) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = as.numeric(scale(b)),
            e = as.numeric(scale(e))
          ) |>
          dplyr::rename(A1_B1_b = b, A1_B1_e = e),
        by = c("A1_B1" = "id")
      ) |>
      # get A1_B2 values
      dplyr::left_join(
        eg_df |>
          dplyr::filter(
            (a>=-5 & a<=-0.1 & d == "a") |  # A1_B1
            (a>=-5 & a<=-0.1 & d == "b") |  # A1_B2
            (a>=0.1 & a<=5 & d == "a") |  # A2_B1
            (a>=0.1 & a<=5 & d == "b")  # A2_B2
          ) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = as.numeric(scale(b)),
            e = as.numeric(scale(e))
          ) |>
          dplyr::rename(A1_B2_b = b, A1_B2_e = e),
        by = c("A1_B2" = "id")
      ) |>
      # get A2_B1 values
      dplyr::left_join(
        eg_df |>
          dplyr::filter(
            (a>=-5 & a<=-0.1 & d == "a") |  # A1_B1
            (a>=-5 & a<=-0.1 & d == "b") |  # A1_B2
            (a>=0.1 & a<=5 & d == "a") |  # A2_B1
            (a>=0.1 & a<=5 & d == "b")  # A2_B2
          ) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = as.numeric(scale(b)),
            e = as.numeric(scale(e))
          ) |>
          dplyr::rename(A2_B1_b = b, A2_B1_e = e),
        by = c("A2_B1" = "id")
      ) |>
      # get A2_B2 values
      dplyr::left_join(
        eg_df |>
          dplyr::filter(
            (a>=-5 & a<=-0.1 & d == "a") |  # A1_B1
            (a>=-5 & a<=-0.1 & d == "b") |  # A1_B2
            (a>=0.1 & a<=5 & d == "a") |  # A2_B1
            (a>=0.1 & a<=5 & d == "b")  # A2_B2
          ) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = as.numeric(scale(b)),
            e = as.numeric(scale(e))
          ) |>
          dplyr::rename(A2_B2_b = b, A2_B2_e = e),
        by = c("A2_B2" = "id")
      ) |>
      dplyr::mutate(
        # distance between A1_B1 and A1_B2
        man_euc_dist_A1_B1_A1_B2 = as.numeric(sqrt((A1_B1_b - A1_B2_b)**2 + (A1_B1_e - A1_B2_e)**2)),
        # distance between A1_B1 and A2_B1
        man_euc_dist_A1_B1_A2_B1 = as.numeric(sqrt((A1_B1_b - A2_B1_b)**2 + (A1_B1_e - A2_B1_e)**2)),
        # distance between A1_B1 and A2_B2
        man_euc_dist_A1_B1_A2_B2 = as.numeric(sqrt((A1_B1_b - A2_B2_b)**2 + (A1_B1_e - A2_B2_e)**2)),
        # distance between A1_B2 and A2_B1
        man_euc_dist_A1_B2_A2_B1 = as.numeric(sqrt((A1_B2_b - A2_B1_b)**2 + (A1_B2_e - A2_B1_e)**2)),
        # distance between A1_B2 and A2_B2
        man_euc_dist_A1_B2_A2_B2 = as.numeric(sqrt((A1_B2_b - A2_B2_b)**2 + (A1_B2_e - A2_B2_e)**2)),
        # distance between A2_B1 and A2_B2
        man_euc_dist_A2_B1_A2_B2 = as.numeric(sqrt((A2_B1_b - A2_B2_b)**2 + (A2_B1_e - A2_B2_e)**2)),
      )

    wide_res |>
      long_format() |>
      dplyr::mutate(gen_euc_dist = as.numeric(gen_euc_dist)) |>
      dplyr::left_join(
        dplyr::select(
          manual_euc_dist, item_nr,
          man_euc_dist_A1_B1_A1_B2, man_euc_dist_A1_B1_A2_B1, man_euc_dist_A1_B1_A2_B2,
          man_euc_dist_A1_B2_A2_B1, man_euc_dist_A1_B2_A2_B2,
          man_euc_dist_A2_B1_A2_B2
        ),
        by = c("item_nr")
      ) |>
      dplyr::rowwise() |>
      dplyr::mutate(max_man_euc_dist = max(c(
        man_euc_dist_A1_B1_A1_B2, man_euc_dist_A1_B1_A2_B1, man_euc_dist_A1_B1_A2_B2,
        man_euc_dist_A1_B2_A2_B1, man_euc_dist_A1_B2_A2_B2,
        man_euc_dist_A2_B1_A2_B2
      ))) |>
      dplyr::ungroup() |>
      dplyr::filter(
        max_man_euc_dist <= 1.5,
        abs(gen_euc_dist - max_man_euc_dist) <= 1e-12
      ) |>
      nrow()
  }, 24)
  # test weighted Euclidean distance is calculated as expected
  testthat::expect_equal({
    weights <- runif(2, 0.1, 100)
    weights_std <- weights / mean(weights)

    wide_res <- eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for_euc(
        c(b, e),
        0:1.5,
        name = "gen_euc_dist",
        weights = weights
      ) |>
      generate(20, silent=TRUE)

    manual_euc_dist <- wide_res |>
      dplyr::left_join(
        eg_df |>
          dplyr::filter((a>=-5 & a<=-0.1) | (a>=0.1 & a<=5)) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = weights_std[1]*as.numeric(scale(b)),
            e = weights_std[2]*as.numeric(scale(e))
          ) |>
          dplyr::rename(A1_b = b, A1_e = e),
        by = c("A1" = "id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::filter((a>=-5 & a<=-0.1) | (a>=0.1 & a<=5)) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = weights_std[1]*as.numeric(scale(b)),
            e = weights_std[2]*as.numeric(scale(e))
          ) |>
          dplyr::rename(A2_b = b, A2_e = e),
        by = c("A2" = "id")
      ) |>
      dplyr::mutate(
        dist_b = A1_b - A2_b,
        dist_e = A1_e - A2_e,
        man_euc_dist = sqrt(dist_b**2 + dist_e**2)
      )

    wide_res |>
      long_format() |>
      dplyr::mutate(gen_euc_dist = as.numeric(gen_euc_dist)) |>
      dplyr::filter(condition != match_null) |>
      dplyr::left_join(
        dplyr::select(manual_euc_dist, item_nr, man_euc_dist),
        by = "item_nr"
      ) |>
      dplyr::filter(abs(gen_euc_dist - man_euc_dist) <= 1e-12) |>
      nrow()
  }, 20)
  # test that weight standardisation can be disabled
  testthat::expect_equal({
    weights <- runif(2, 0.1, 100)

    wide_res <- eg_df |>
      set_options(id_col = "id") |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      control_for_euc(
        c(b, e),
        0:10,
        name = "gen_euc_dist",
        weights = weights,
        standardise_weights = FALSE
      ) |>
      generate(12, silent=TRUE)

    manual_euc_dist <- wide_res |>
      dplyr::left_join(
        eg_df |>
          dplyr::filter((a>=-5 & a<=-0.1) | (a>=0.1 & a<=5)) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = weights[1]*as.numeric(scale(b)),
            e = weights[2]*as.numeric(scale(e))
          ) |>
          dplyr::rename(A1_b = b, A1_e = e),
        by = c("A1" = "id")
      ) |>
      dplyr::left_join(
        eg_df |>
          dplyr::filter((a>=-5 & a<=-0.1) | (a>=0.1 & a<=5)) |>
          dplyr::select(id, b, e) |>
          dplyr::mutate(
            b = weights[1]*as.numeric(scale(b)),
            e = weights[2]*as.numeric(scale(e))
          ) |>
          dplyr::rename(A2_b = b, A2_e = e),
        by = c("A2" = "id")
      ) |>
      dplyr::mutate(
        dist_b = A1_b - A2_b,
        dist_e = A1_e - A2_e,
        man_euc_dist = sqrt(dist_b**2 + dist_e**2)
      )

    wide_res |>
      long_format() |>
      dplyr::mutate(gen_euc_dist = as.numeric(gen_euc_dist)) |>
      dplyr::filter(condition != match_null) |>
      dplyr::left_join(
        dplyr::select(manual_euc_dist, item_nr, man_euc_dist),
        by = "item_nr"
      ) |>
      dplyr::filter(abs(gen_euc_dist - man_euc_dist) <= 1e-12) |>
      nrow()
  }, 12)
  # test that standard and non-standard evaluation are equivalent
  testthat::expect_equal(
    {
      set.seed(77)
      x <- eg_df |>
        set_options(id_col = "id") |>
        split_by(a, -5:-0.1 ~ 0.1:5) |>
        control_for_euc(
          c(b, e),
          0:1.5,
          name = "gen_euc_dist"
        ) |>
        generate(20, silent=TRUE) |>
        as.data.frame()

      attr(x, "LexOPS_info") <- NULL

      x
    },
    {
      set.seed(77)
      x <- eg_df |>
        set_options(id_col = "id") |>
        split_by(a, -5:-0.1 ~ 0.1:5) |>
        control_for_euc(
          c("b", "e"),
          c(0, 1.5),
          name = "gen_euc_dist",
          standard_eval = TRUE
        ) |>
        generate(20, silent=TRUE) |>
        as.data.frame()

      attr(x, "LexOPS_info") <- NULL

      x
    }
  )
  # test that control_for_euc() can be the first function in a pipeline
  testthat::expect_equal(
    eg_df |>
      # rename to default id_col
      dplyr::rename(string = id) |>
      control_for_euc(
        c(b, e),
        0:0.75,
        name = "gen_euc_dist"
      ) |>
      split_by(a, -5:-0.1 ~ 0.1:5) |>
      generate(20, silent=TRUE) |>
      nrow(),
    20
  )
})

Try the LexOPS package in your browser

Any scripts or data that you put into this service are public.

LexOPS documentation built on Dec. 1, 2026, 5:06 p.m.