R/generate.R

Defines functions generate.find_fun_matches generate.are_matches_inclusive generate.find_matches generate.filter_tol_keep generate.filter_tol generate.check generate

Documented in generate

#' Generate stimuli
#'
#' Generates the stimuli from the data frame after it has been passed through \code{\link{split_by}}, and optionally, \code{\link{control_for}}. Will generate `n` items per condition. If <`n` items can be generated, will generate as many as possible given the experiment's design.
#'
#' @param x A LexOPS_pipeline object resulting from one of \code{\link{split_by}}, \code{\link{control_for}}, etc..
#' @param n The number of strings per condition (default = 20). Set to `"all"` to generate as many as possible.
#' @param match_null The condition that items should be matched to. Should be a string indicating condition (e.g. `"A1_B2_C1"`), or a string indicating one of the following options: `"balanced"` for randomly ordered null conditions with (as close to as possible) equal number of selections for each condition (default), "inclusive" to match each condition within the tolerances to every other condition, `"first"` for the lowest condition (e.g. `"A1"` or `"A1_B1_C1_D1"`, etc.), `"random"` for randomly selected null condition each iteration.
#' @param seed Deprecated: set seeds externally (e.g., `set.seed()`).
#' @param silent Logical: should output to the console (via `cat()`) be suppressed? Default is FALSE.
#' @param is_shiny Allows printing in a `shiny` context with \code{shinyjs::\link[shinyjs]{html}}. Outputs from the `cat()` function are stored in the div with id "gen_console". Default is FALSE.
#'
#' @returns The generated stimuli, as a dataframe of class `LexOPS_pipeline`.
#' @examplesIf rlang::is_installed("lexopsdata") & rlang::is_installed("stringdist")
#'
#' library(lexopsdata)
#'
#' # Generate 10 words per condition, for design with 3 levels of syllables, controlled for frequency
#' lexops |>
#'   split_by(Syllables.CMU, 1:3 ~ 4:6 ~ 7:20) |>
#'   control_for(Zipf.SUBTLEX_UK, -0.2:0.2) |>
#'   generate(n = 10)
#'
#' # Generate 2 levels of bigram probability, controlling for frequency and length
#' # (Note that the matching null is balanced across all stimuli)
#' # (Also note that the data is filtered by proportion known to be >75%)
#' lexops |>
#'   subset(PK.Brysbaert >= .75) |>
#'   split_by(BG.SUBTLEX_UK, 0.001:0.003 ~ 0.009:0.011) |>
#'   control_for(Zipf.SUBTLEX_UK, -0.2:0.2) |>
#'   control_for(Length) |>
#'   generate(n = 10, match_null = "balanced")
#'
#' # Generate stimuli for a concreteness x valence (2 x 3) design
#' # (Note that abstract, neutral is set as the matching null)
#' lexops |>
#'   split_by(CNC.Brysbaert, 1:2 ~ 4:5) |>
#'   split_by(VAL.Warriner, 1:3 ~ 4.5:5.5 ~ 7:9) |>
#'   control_for(Zipf.SUBTLEX_UK, -0.25:0.25) |>
#'   control_for(Length) |>
#'   generate(n = 10, match_null = "A2_B2")
#'
#' # As above but with inclusive tolerance
#' # (all words are within the specified tolerances relative to each other)
#' lexops |>
#'   split_by(CNC.Brysbaert, 1:2 ~ 4:5) |>
#'   split_by(VAL.Warriner, 1:3 ~ 4.5:5.5 ~ 7:9) |>
#'   control_for(Zipf.SUBTLEX_UK, -0.25:0.25) |>
#'   control_for(Length) |>
#'   generate(n = 10, match_null = "inclusive")
#'
#' # Bypass non-standard evaluation
#' lexops |>
#'  split_by("Syllables.CMU", list(c(1, 3), c(4, 6), c(7, 20)), standard_eval = TRUE) |>
#'  control_for("Zipf.SUBTLEX_UK", c(-0.2, 0.2), standard_eval = TRUE) |>
#'  generate(n = 10)
#'
#' # Create two levels of arousal, controlling for orthographic Levenshtein distance
#' library(stringdist)
#' lexops |>
#'  split_by(AROU.Warriner, 1:3 ~ 6:9) |>
#'  control_for_map(stringdist, string, 0:4, method="lv") |>
#'  generate(10)
#'
#' # Create two levels of arousal, controlling for phonological similarity
#' library(stringdist)
#' lexops |>
#'  split_by(AROU.Warriner, 1:3 ~ 6:9) |>
#'  control_for_map(stringdist, eSpeak.br_1letter, 0:2, method="lv") |>
#'  generate(10)
#'
#' # Create two levels of arousal, controlling for phonological Levenshtein distance, and rhyme
#' library(stringdist)
#' lexops |>
#'  split_by(AROU.Warriner, 1:3 ~ 6:9) |>
#'  control_for(Rhyme.eSpeak.br) |>
#'  control_for_map(stringdist, eSpeak.br_1letter, 0:2, method="lv") |>
#'  generate(10)
#'
#' # A similar design to that above, but with 3 levels of valence, and inclusive matching
#' library(stringdist)
#' lexops |>
#'  split_by(VAL.Warriner, 1:3 ~ 4.5:5.5 ~ 7:9) |>
#'  control_for(Rhyme.eSpeak.br) |>
#'  control_for_map(stringdist, eSpeak.br_1letter, 0:2, method="lv") |>
#'  generate(10, match_null = "inclusive")
#'
#' @seealso \code{\link{lexops}} for the data frame used in the examples.
#'
#' @export
#' @importFrom stats setNames

generate <- function(x, n=20, match_null = "balanced", seed = NA, silent = FALSE, is_shiny = FALSE) {

  # give informative error if the user tries to provide a seed
  if (!is.na(seed)) {
    stop("The seed argument is deprecated. Seeds are now set externally. For more information see https://github.com/JackEdTaylor/LexOPS/releases/tag/0.5.0")
  }

  if (is_shiny) {
    # if in a shiny context, replace the base cat() function with one which captures the console output
    cat <- function(str) shinyjs::html("gen_console", sprintf("%s", str))
  }

  # get pipeline info
  lp_info <- if (is.LexOPS_pipeline(x)) {
    if (is.null(x$info)) {
      list()
    } else {
      x$info
    }
  } else {
    list()
  }

  # extract df if class is LexOPS_pipeline
  if (is.LexOPS_pipeline(x)) {
    df <- x$df
  } else {
    stop("x must be a LexOPS_pipeline")
  }

  # get options from pipeline info
  if (!is.null(lp_info$options)) {
    id_col <- lp_info$options$id_col
    cond_col <- lp_info$options$cond_col
    cond_col_regex <- sprintf("^%s_[A-Z]$", cond_col)
  } else {
    id_col <- "string"
    if (!id_col %in% colnames(df) & is.data.frame(df)) {
      df[[id_col]] <- 1:nrow(df)  # use row number as id if there isn't one
      warning("No id_col detected; will use current row numbers (after any subsetting).")
    }
    cond_col <- "LexOPS_splitCond"
    cond_col_regex <- sprintf("^%s_[A-Z]$", cond_col)
  }

  # check for problems with arguments
  generate.check(df, n, match_null, id_col, cond_col, is_shiny, lp_info)

  # get the columns containing the split data
  LexOPS_splitCols <- colnames(df)[grepl(cond_col_regex, colnames(df))]

  # create new column which gives the cell of the design that each item belongs to
  if (length(LexOPS_splitCols) > 0) {
    split_values <- lapply(LexOPS_splitCols, function(col) as.character(df[[col]]))
    condition <- do.call(paste, c(split_values, sep = "_"))
    missing_split <- Reduce(`|`, lapply(split_values, is.na))
    condition[missing_split] <- NA_character_
    df[[cond_col]] <- condition
  } else {
    df[[cond_col]] <- NA_character_
  }
  # remove strings that are members of no condition
  df <- df[!is.na(df[[cond_col]]), , drop = FALSE]

  all_conds <- sort(unique(df[[cond_col]]))

  # check match_null is an expected value
  if (!match_null %in% c(all_conds, "inclusive", "balanced", "random", "first")) stop('Unknown match_null; expected "inclusive", "random", "balanced", "first", or a specific condition (e.g. "A2_B1_C1")')

  # if no controls, just return the df with the condition variable, otherwise generate matches
  if (!is.null(lp_info$controls) | !is.null(lp_info$control_functions)) {

    # get the absolute smallest number of possible match rows (a count of the least frequent condition)
    # count rows per condition and take minimum
    cond_table <- table(df[[cond_col]])
    min_nr_of_match_rows <- min(as.integer(cond_table))
    # if n is "all", set to the largest possible number of match rows
    if (n == "all") {
      n <- min_nr_of_match_rows
      n_all <- TRUE
    } else {
      n_all <- FALSE
    }
    # give warning if min_nr_of_match_rows < n, as this means n is definitely not achievable
    if (min_nr_of_match_rows < n) {

      n_too_large_message <- if (is.null(lp_info$random_splits) | length(lp_info$random_splits)==0) {
        sprintf("n is too large; requested n of %i, but the condition with the fewest members has %i entries. Ensure n <= %i. Will generate as many stimuli as possible.", n, min_nr_of_match_rows, min_nr_of_match_rows)
      } else {
        sprintf("n is too large; requested n of %i, but the condition with the fewest members has %i entries. Ensure n <= %i. You may also increase the number of candidates by setting equal_size=TRUE in split_random(). Will generate as many stimuli as possible.", n, min_nr_of_match_rows, min_nr_of_match_rows)
      }
      warning(n_too_large_message)
    }

    # specify exactly how many null conditions are needed
    null_cond_n <- if (n < min_nr_of_match_rows) n else min_nr_of_match_rows

    # specify the null conditions
    null_conds <- if (match_null == "first") {
      rep(sort(all_conds)[1], null_cond_n)
    } else if (match_null == "random") {
      sample(all_conds, null_cond_n, replace = TRUE)
    } else if (match_null == "balanced") {
      if (n_all) warning('`match_null="balanced"` may not work when `n="all"`. Check distributions of match_null in the output.')
      # As close to equal number of each condition as possible, randomly ordered.
      # If doesn't perfectly divide, the condition(s) which are over-represented are also randomly chosen.
      # permute conditions, repeat to length and resample to randomise order
      perm <- sample(all_conds, length(all_conds))
      rep_len(perm, null_cond_n)[sample(null_cond_n)]
    } else if (match_null == "inclusive") {
      # same as balanced for starting match null
      perm <- sample(all_conds, length(all_conds))
      rep_len(perm, null_cond_n)[sample(null_cond_n)]
    } else if (match_null %in% all_conds) {
      rep(match_null, null_cond_n)
    }

    # iterate over all items in the null_condition, and for each, generate row of matched stimuli if possible
    n_tried <- 0
    n_tried_this_n_generated <- 0  # increases by 1 each iter but resets to 0 each time a row of matches is successfully generated
    n_generated <- 0
    items_tried_this_generated <- c()
    out <- matrix(ncol=length(all_conds)+1, nrow=n)
    printing_points <- round(seq(0, n, n/20))
    successful_iterations <- c()
    control_for_map_values <- list()
    control_for_map_value_rows <- integer()
    control_function_names <- if (length(lp_info$control_functions) > 0) {
      sapply(lp_info$control_functions, function(cont) cont[[1]])
    }
    # Index rows once so each candidate attempt only inspects the relevant condition.
    df_rows <- seq_len(nrow(df))
    rows_by_condition <- split(df_rows, df[[cond_col]])
    used_rows <- rep(FALSE, nrow(df))

    while(n_generated < n) {
      n_tried <- n_tried + 1
      n_tried_this_n_generated <- n_tried_this_n_generated + 1

      this_match_null <- null_conds[n_generated+1]
      null_rows <- rows_by_condition[[this_match_null]]
      null_rows <- null_rows[!used_rows[null_rows] & !df[[id_col]][null_rows] %in% items_tried_this_generated]
      null_item_bank <- df[[id_col]][null_rows]

      if (length(null_item_bank) == 0) {
        if (n_all) {
          if (!silent) cat(sprintf("Generated %i (%i iterations, %.2f success rate)\r", n_generated, n_tried, n_generated/n_tried))
        } else {
          warning_text <- sprintf("\nFailed to generate any new matches for matched row %i (all %i candidate null matches were tried)", n_generated + 1, n_tried_this_n_generated)
          if (is_shiny) {
            cat(warning_text)
          } else {
            warning(warning_text)
          }
        }
        break
      }

      this_item <- sample(null_item_bank, 1)
      items_tried_this_generated <- c(items_tried_this_generated, this_item)
      target_row <- match(this_item, df[[id_col]])

      matches <- sapply(all_conds[all_conds != this_match_null], function(cnd) {
        candidate_rows <- rows_by_condition[[cnd]]
        candidate_rows <- candidate_rows[!used_rows[candidate_rows]]
        m <- generate.find_matches(
          df,
          target = this_item,
          vars = lp_info$controls,
          matchCond = this_match_null,
          id_col = id_col,
          cond_col = cond_col,
          candidate_rows = sort(c(candidate_rows, target_row)),
          target_row = target_row
        )
        m <- generate.find_fun_matches(
          m,
          target = this_item,
          vars_pre_calc = lp_info$control_functions,
          matchCond = this_match_null,
          id_col = id_col,
          cond_col = cond_col,
          target_row = match(this_item, m[[id_col]]),
          inclusive = match_null == "inclusive"
        )
        # remove the target item
        m <- m[m[[id_col]]!=this_item, ]

        if (nrow(m)==0) {
          item_out <- NA
          } else {
            # pick a match randomly
            item_out <- sample(m[[id_col]], 1)
            # store any control_for_map values
            if (length(lp_info$control_functions) > 0) {
              item_row <- match(item_out, df[[id_col]])
              out_cont_map_val <- sapply(lp_info$control_functions, function(cont) {
                # get the representations of the items in the given column
                this_item_rep <- df[[ cont[[3]] ]][target_row]
                out_rep <- df[[ cont[[3]] ]][item_row]
                # get the value from the function
                unname(cont[[2]](out_rep, this_item_rep))
              })
              names(out_cont_map_val) <- control_function_names
              out_val <- item_out
              names(out_val) <- id_col
              newrow <- as.data.frame(as.list(c(out_val, out_cont_map_val)), stringsAsFactors = FALSE)
              control_for_map_values[[length(control_for_map_values) + 1]] <<- newrow
              control_for_map_value_rows <<- c(control_for_map_value_rows, item_row)
              # ensure this_item row exists in control_for_map_values
              if (!(target_row %in% control_for_map_value_rows)) {
                this_item_map_val <- sapply(lp_info$control_functions, function(cont) {
                  this_item_rep <- df[[ cont[[3]] ]][target_row]
                  unname(cont[[2]](this_item, this_item))
                })
                names(this_item_map_val) <- control_function_names
                this_item_val <- this_item
                names(this_item_val) <- id_col
                newrow2 <- as.data.frame(as.list(c(this_item_val, this_item_map_val)), stringsAsFactors = FALSE)
                control_for_map_values[[length(control_for_map_values) + 1]] <<- newrow2
                control_for_map_value_rows <<- c(control_for_map_value_rows, target_row)
              }

            }
          }

        item_out
      })
      # add the target item
      matches[this_match_null] <- this_item
      # ensure ordered correctly (e.g. A1, A2, A3)
      matches <- matches[match(all_conds, names(matches))]

      # check the matches are inclusive if match_null = "inclusive"
      if (match_null == "inclusive") {
        matches <- generate.are_matches_inclusive(
          df = df,
          matches,
          vars=lp_info$controls, vars_pre_calc = lp_info$control_functions,
          matchCond=this_match_null, id_col, cond_col,
          candidate_rows = df_rows[!used_rows | df_rows == target_row]
        )
      }

      # if n=="all", print progress every 100 iterations
      if (!silent) {
        if (n_tried%%100==0 & n_all) {
          if (all(!is.na(matches))) {
            cat(sprintf("Generated %i (%i iterations, %.2f success rate)\r", n_generated+1, n_tried, (n_generated+1)/n_tried))
          } else {
            cat(sprintf("Generated %i (%i iterations, %.2f success rate)\r", n_generated, n_tried, n_generated/n_tried))
          }
        }
      }

      if (all(!is.na(matches))) {
        this_match_null_out <- if (match_null=="inclusive") NA else this_match_null  # if match_null is inclusive, don't store initial match_nullvalue
        out[n_generated + 1, ] <- c(matches, this_match_null_out)
        used_rows[match(matches, df[[id_col]])] <- TRUE
        n_generated <- n_generated + 1
        successful_iterations <- c(successful_iterations, n_tried)
        n_tried_this_n_generated <- 0
        items_tried_this_generated <- c()
        if (!silent) {
          if (n_generated %in% printing_points & !n_all) {
            cat(sprintf("Generated %i/%i (%i%%). %i total iterations, %.2f success rate.\r", n_generated, n, round(n_generated/n*100), n_tried, n_generated/n_tried))
          }
        }
      }

    }
    if (!silent & !is_shiny) cat(sprintf("\n"))

    # create meta_df
    meta_df <- df

    # add control_for_map() values if any (merge preserving order)
    if (length(lp_info$control_functions) > 0 & length(control_for_map_values) > 0) {
      control_for_map_values <- do.call(rbind, control_for_map_values)
      # if there are more >2 factorial cells and inclusive matching is used, return a value of NA, rather than just the first, initial value that was calculated for the matched set
      if (match_null == "inclusive" && length(all_conds) > 2) {
        for (cont in lp_info$control_functions) {
          if (is.null(cont$inclusive_max)) {
            control_for_map_values[[cont[[1]]]] <- NA
          }
        }
      }
      has_group_control <- any(vapply(lp_info$control_functions, function(cont) !is.null(cont$inclusive_max), logical(1)))
      if (match_null == "inclusive" && has_group_control) {
        complete_rows <- stats::complete.cases(out[, seq_along(all_conds), drop = FALSE])
        generated_ids <- unique(as.vector(out[complete_rows, seq_along(all_conds), drop = FALSE]))
        repeated_generated_ids <- control_for_map_values[[id_col]] %in% generated_ids &
          duplicated(control_for_map_values[[id_col]])
        control_for_map_values <- control_for_map_values[!repeated_generated_ids, , drop = FALSE]
      }
      meta_df <- merge(meta_df, control_for_map_values, by = id_col, all.x = TRUE, sort = FALSE)
    }

    df <- as.data.frame(out, stringsAsFactors = FALSE)
    colnames(df) <- c(all_conds, "match_null")
    # drop rows with NA in any of the condition columns (allow NA in match_null)
    cols_check <- setdiff(colnames(df), "match_null")
    if (nrow(df) > 0) {
      df <- df[stats::complete.cases(df[, cols_check, drop = FALSE]), , drop = FALSE]
    }
    if (match_null == "inclusive" && nrow(df) > 0) {
      for (cont in lp_info$control_functions) {
        if (is.null(cont$inclusive_max)) next
        for (row in seq_len(nrow(df))) {
          matched_ids <- unlist(df[row, all_conds, drop = FALSE], use.names = FALSE)
          group_distance <- cont$inclusive_max(matched_ids)
          meta_rows <- match(matched_ids, meta_df[[id_col]])
          meta_df[[cont[[1]]]][meta_rows] <- group_distance
        }
      }
    }
    # add the item number as item_nr and put it first
    df$item_nr <- seq_len(nrow(df))
    df <- df[c("item_nr", setdiff(names(df), "item_nr"))]
    # add the original df to the attributes
    lp_info$meta_df <- meta_df
    # add the success rate to the attributes
    lp_info$success_rate <- n_generated/n_tried
    # add a vector of the iteratons that were successful
    lp_info$successful_iterations <- successful_iterations

  }

  # add a marker to the attributes that df has gone through the generate function
  lp_info$generated <- TRUE

  # add the info as attributes to the output object
  attr(df, "LexOPS_info") <- lp_info

  df
}

# function to check supplied arguments makes sense
generate.check <- function(df, n, match_null, id_col, cond_col, is_shiny, lp_info) {

  # check that id_col uniquely identifies the rows
  if (length(unique(df[[id_col]])) != nrow(df)) stop("LexOPS assumes that id_col uniquely identifies the rows")

  # warn about coercion if column id_col is a factor
  if (is.factor(df[[id_col]])) warning(sprintf("id_col '%s' is a factor; will be coerced to character vector representation of factor levels", id_col))

  # check n is a number or expected string
  if (!is.numeric(n) & n != "all") stop(sprintf('n must be numeric or a string of value "all"'))

  # check the splits are defined
  if (length(lp_info$splits)==0) stop("No splits defined - see ?LexOPS::generate for example usage of generate()")

  # check the controls are defined
  if (length(lp_info$controls)==0 & length(lp_info$control_functions)==0) stop("No controls defined - see ?LexOPS::generate for example usage of generate()")

  # check that the conditions are present in the attributes
  if (is.null(cond_col)) {
    # if the column containing the condition info is missing and not defined manually, throw error
    stop("Could not identify split conditions column! Make sure you run split_by() before generate().")
  }
  # if control_for() has been run (can tell from attributes), check the specified columns exist
  if (!is.null(lp_info$controls)) {
    controls_exist <- sapply(lp_info$controls, function(cont) {cont[[1]] %in% colnames(df)})
    if (!(all(controls_exist))) stop(sprintf("%i unknown control columns. Check columns specified in control_for() are in df.", length(controls_exist[!controls_exist])))
  }
  # if control_for_fun() has been run, check the column to be fed to the function exists in df
  if (!is.null(lp_info$control_functions)) {
    controls_exist <- sapply(lp_info$control_functions, function(cont) {cont[[3]] %in% colnames(df)})
    if (!(all(controls_exist))) stop(sprintf("%i unknown control columns. Check columns specified in control_for() are in df.", length(controls_exist[!controls_exist])))
  }
}

# function to filter exactly for categories, and with tolerances for numeric in a vectorised manner
generate.filter_tol <- function(df_matches, vars) {
  keep <- generate.filter_tol_keep(df_matches, vars)
  df_matches[keep, , drop = FALSE]
}

generate.filter_tol_keep <- function(df_matches, vars, rows = seq_len(nrow(df_matches))) {
  keep <- rep(TRUE, length(rows))
  for (tol in vars) {
    values <- df_matches[[tol[[1]]]][rows]
    keep_this <- rep(TRUE, length(rows))
    if (is.numeric(values) && length(tol) >= 3) {
      keep_this <- values >= tol[[3]] + tol[[2]][1] & values <= tol[[3]] + tol[[2]][2]
    } else if (is.numeric(values)) {
      keep_this <- values == tol[[2]]
    } else {
      keep_this <- values == tol[[2]]
    }
    keep <- keep & keep_this
  }
  keep[is.na(keep)] <- FALSE  # any that evaluate to NA should also be excluded
  keep
}

# function to find matches for a particular item
generate.find_matches <- function(df, target, vars, matchCond, id_col, cond_col, candidate_rows = NULL, target_row = NULL) {
  # if no controls, return the df unchanged
  if (length(vars)==0) {
    if (is.null(candidate_rows)) return(df)
    return(df[candidate_rows, , drop = FALSE])
  }
  # get a copy of df excluding the null condition, but keep the target item
  if (is.null(candidate_rows)) {
    candidate_rows <- which(df[[cond_col]] != matchCond | df[[id_col]] == target)
  }
  if (is.null(target_row)) target_row <- match(target, df[[id_col]])
  # add a 2nd (for categorical) or 3rd (for numeric) item to each control's list, indicating the value for the string being matched to
  vars <- lapply(vars, function(cont) {
    cont_val <- if (is.factor(df[[cont[[1]]]])) {
      as.character(df[[cont[[1]]]][target_row])
    } else {
      df[[cont[[1]]]][target_row]
    }
    if (is.list(cont)) append(cont, cont_val) else list(cont, cont_val)
  })
  # for each control, filter out non-suitable matches for this item
  keep <- generate.filter_tol_keep(df, vars, candidate_rows)
  df_matches_filt <- df[candidate_rows[keep], , drop = FALSE]

  df_matches_filt
}

# function to check whether the matches are inclusive (necessary if match_null = "inclusive")
# This treats each possible condition for the current item as the match null for one iteration, and tests that all other items are suitable matches
# if TRUE, will return the matches unchanged, else will return same vector with all values replaced by NAs
generate.are_matches_inclusive <- function(df, matches, vars, vars_pre_calc, matchCond, id_col, cond_col, candidate_rows = seq_len(nrow(df))) {
  # if there are NAs in matches, return NAs
  if (any(is.na(matches))) return(rep(NA, length(matches)))
  # if no controls, return matches unchanged
  if (length(vars)==0 && length(vars_pre_calc)==0) return(matches)
  # get the selected rows
  matched_rows <- match(unname(matches), df[[id_col]])
  selected_rows <- candidate_rows[candidate_rows %in% matched_rows]
  group_controls <- Filter(function(cont) !is.null(cont$inclusive_max), vars_pre_calc)
  vars_pre_calc <- Filter(function(cont) is.null(cont$inclusive_max), vars_pre_calc)
  # check items are matched inclusively
  are_inclusive <- lapply(matches, function(this_item) {
    # get this item's condition
    matchCond_this_item <- names(matches)[matches==this_item]
    this_item_row <- match(this_item, df[[id_col]])
    this_candidate_rows <- selected_rows[df[[cond_col]][selected_rows] != matchCond_this_item | selected_rows == this_item_row]
    # get list of suitable matches based on controls
    df_matches_this_item <- generate.find_matches(df, this_item, vars, matchCond_this_item, id_col, cond_col, this_candidate_rows, this_item_row)
    # get a similar list, but mapping any specified functions
    df_matches_this_item_funs <- generate.find_fun_matches(df[this_candidate_rows, , drop = FALSE], this_item, vars_pre_calc, matchCond_this_item, id_col, cond_col)
    # check the other items are in there, and return this value
    all(matches[matches != this_item] %in% df_matches_this_item[[id_col]]) & all(matches[matches != this_item] %in% df_matches_this_item_funs[[id_col]])
  })
  are_group_controls_inclusive <- vapply(group_controls, function(cont) {
    group_distance <- cont$inclusive_max(unname(matches))
    !is.na(group_distance) && group_distance >= cont[[4]][1] && group_distance <= cont[[4]][2]
  }, logical(1))
  # leave unchanged if inclusive, otherwise return NAs
  if (all(unlist(are_inclusive)) && all(are_group_controls_inclusive)) {
    matches
  } else {
    setNames(rep(NA, length(matches)), names(matches))
  }
}

# function to find matches for a particular item using functions defined by `control_for_fun()`
generate.find_fun_matches <- function(df, target, vars_pre_calc, matchCond, id_col, cond_col, target_row = NULL, inclusive = FALSE) {
  # if no control functions, return the df unchanged
  if (length(vars_pre_calc)==0) return(df)

  # if df has a 0 rows (e.g. if generate.find_matches() found no matches), return df unchanged
  if (nrow(df)==0) return(df)

  if (is.null(target_row)) target_row <- match(target, df[[id_col]])

  # get the new columns' values for the target item
  target_vals <- sapply(vars_pre_calc, function(x) {
    fun <- x[[2]]
    var <- x[[3]]
    tol <- x[[4]]
    target_input <- df[[var]][target_row]
    fun(target_input, target_input)
  })

  # get a copy of df excluding the null condition and the target item
  df_matches <- df[df[[cond_col]] != matchCond | df[[id_col]] == target, ]

  # calculate the new columns based on the supplied functions and arguments
  # (each item of var should have a structure of `list(name, fun, var, tol)`)
  func_col_names <- sapply(vars_pre_calc, function(x) x[[1]])
  # calculate new columns as list and bind to df_matches
  # build new columns with strict length checks
  n_rows_matches <- nrow(df_matches)
  newcols <- lapply(seq_along(vars_pre_calc), function(i) {
    x <- vars_pre_calc[[i]]
    fun <- x[[2]]
    var <- x[[3]]
    col_name <- func_col_names[[i]]
    arg1 <- df_matches[[ var ]]
    target_input <- df[[ var ]][target_row]
    res <- tryCatch(fun(arg1, target_input), error = function(e) stop(sprintf("control function '%s' error when applied to candidates: %s", col_name, conditionMessage(e))))
    # drop names to avoid rowname-based alignment during cbind
    res <- unname(res)
    if (length(res) == 1) {
      rep(res, n_rows_matches)
    } else if (length(res) == n_rows_matches) {
      res
    } else if (length(res) == 0) {
      rep(NA, n_rows_matches)
    } else {
      stop(sprintf("control function '%s' returned length %d but expected 1 or %d", col_name, length(res), n_rows_matches))
    }
  })
  names(newcols) <- func_col_names
  newcols_df <- as.data.frame(newcols, stringsAsFactors = FALSE, check.names = FALSE)
  # cbind but ensure no rownames remain to prevent alignment by name in bind
  rownames(newcols_df) <- NULL
  rownames(df_matches) <- NULL
  df_matches <- data.frame(df_matches, newcols_df, stringsAsFactors = FALSE, check.names = FALSE)

  # create vars list which will be used for matching purposes
  vars <- lapply(1:length(vars_pre_calc), function(cont_nr) {
    cont <- vars_pre_calc[[cont_nr]]
    col_name <- func_col_names[[cont_nr]]
    if (length(cont) >= 4) {
      tol <- cont[[4]]
      if (inclusive && !is.null(cont$inclusive_max)) tol[1] <- -Inf
      list(col_name, tol)
    } else {
      list(col_name)
    }
  })

  # add a 2nd (for categorical) or 3rd (for numeric) item to each control's list, indicating the value for the string being matched to
  vars <- lapply(1:length(vars), function(cont_nr) {
    cont <- vars[[cont_nr]]
    fun <- vars_pre_calc[[cont_nr]][[2]]
    var <- vars_pre_calc[[cont_nr]][[3]]
    cont_val <- target_vals[[cont_nr]]
    if (is.list(cont)) append(cont, cont_val) else list(cont, cont_val)
  })

  # for each control, filter out non-suitable matches for this item
  df_matches_filt <- generate.filter_tol(df_matches, vars)

  df_matches_filt
}

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.