Nothing
#' Get suitable matches for a single item on one or several dimensions.
#'
#' Suggests items that are suitable matches for a target item, based on selected variables of a data frame. Note that unlike functions in the generate pipeline (e.g. \code{\link{control_for}}), multiple variables' tolerances can be defined in one function.
#'
#' @param df A data frame to reorder, containing the target string (default = `lexops`).
#' @param target The target string
#' @param ... Should specify the variables and tolerances in the form `Length = 0:0, Zipf.SUBTLEX_UK = -0.1:0.1, PoS.SUBTLEX_UK`. Numeric variables can include tolerances (as elements 2:3 of a vector). Numeric variables with no tolerances will be matched exactly.
#' @param id_col A character vector specifying the column identifying unique observations (e.g. in `lexopsdata::lexops`, the `id_col` is `"string"`).
#' @param filter Logical. If TRUE, matches outside the tolerances specified in vars are removed. If FALSE, a new column, matchFilter is calculated indicating whether or not the string is within all variables' tolerances. (Default = TRUE.)
#' @param standard_eval Logical; bypasses non-standard evaluation, and allows more standard R object of list. If `TRUE`, `...` should be a single list specifying the variables to match by and their tolerances, in the form `list("numericVariable1Name", c("numericVariable2Name", -1.5, 3), "characterVariableName")`. Default = `FALSE`.
#'
#' @returns An object of class `data.frame` derived from `df`. If `filter == TRUE`, will only contain matches. If `filter == FALSE`, will be the original `df` object, with a new column, `"matchFilter"`.
#' @examplesIf rlang::is_installed("lexopsdata")
#'
#' library(lexopsdata)
#'
#' # Match by number of syllables exactly
#' match_item(lexops, "thicket", Syllables.CMU)
#'
#' # Match by number of syllables exactly, but keep all entries in the original dataframe
#' match_item(lexops, "thicket", Syllables.CMU, filter = FALSE)
#'
#' # Match by number of syllables exactly, and rhyme
#' match_item(lexops, "thicket", Syllables.CMU, Rhyme.CMU)
#'
#' # Match by length exactly, and closely by frequency (within 0.2 Zipf either way)
#' match_item(lexops, "thicket", Length, Zipf.SUBTLEX_UK = -0.2:0.2)
#'
#' # The syntax supports matching by multiple variables
#' match_item(
#' lexops,
#' "elephant",
#' BG.SUBTLEX_UK = -0.005:0.005,
#' Length = 0:0,
#' Zipf.SUBTLEX_UK = -0.1:0.1,
#' PoS.SUBTLEX_UK,
#' RT.ELP = -10:10
#' )
#'
#' # Match using standard evaluation
#' match_item(
#' lexops,
#' "thicket",
#' list("Length", c("Zipf.SUBTLEX_UK", -0.2, 0.2)),
#' standard_eval = TRUE
#' )
#'
#' # Find matches within an orthographic levenshtein distance of 5 from "thicket":
#' library(dplyr)
#' library(stringdist)
#' targ_word <- "thicket"
#' lexops |>
#' mutate(old = stringdist(targ_word, string, method="lv")) |>
#' match_item(targ_word, old = 0:5)
#'
#' # Find matches within a phonological levenshtein distance of 2 from "thicket":
#' # (note that this method requires 1-letter phonological transcriptions)
#' library(dplyr)
#' library(stringdist)
#' targ_word <- "thicket"
#' targ_word_pronun <- lexops |>
#' filter(string == "thicket") |>
#' pull(eSpeak.br_1letter)
#' lexops |>
#' mutate(pld = stringdist(targ_word_pronun, eSpeak.br_1letter, method="lv")) |>
#' match_item(targ_word, pld = 0:2)
#'
#' @seealso \code{\link[lexopsdata]{lexops}} for the default data frame and associated variables.
#'
#' @export
match_item <- function(df = LexOPS::lexops, target, ..., id_col = "string", filter = TRUE, standard_eval = FALSE) {
if (standard_eval) {
vars <- (...)
} else {
vars <- substitute(c(...)) |>
parse_ellipsis()
}
# check the df is a dataframe
if (!is.data.frame(df)) stop(sprintf("Expected df to be of class data frame, not %s", class(df)))
# check this dataframe doesn't include a column called euclidean_distance; if it does, remove it and throw a warning
if ("euclidean_distance" %in% colnames(df)) {
warning('"euclidean_distance" column will be ignored, as this is overwritten by `match_item()`')
df$euclidean_distance <- NULL
}
# check id_col is a character vector
if (!is.character(id_col)) stop(sprintf("Expected id_col to be of class character, not %s", class(id_col)))
# check all variables in vars are in the dataframe
varsPresent <- sapply(vars, function(listobj) listobj[1] %in% colnames(df))
if (!all(varsPresent)) {
stop(
sprintf(
"Missing %i variables in df:\n\t%s",
length(vars[!varsPresent]),
paste(sapply(vars[!varsPresent], function(listobj) listobj[1]), collapse="\n\t")
)
)
}
# check numeric and non-numeric variables are correctly specified
varsIncorrectlySpecified <- sapply(vars, function(listObj) {
(!is.numeric(df[[listObj[1]]]) & length(listObj)==3) | !(length(listObj) %in% c(1, 3))
})
if (any(varsIncorrectlySpecified)) {
stop(
sprintf(
"%i variables misspecified:\n\t%s",
length(vars[varsIncorrectlySpecified]),
paste(sapply(vars[varsIncorrectlySpecified], function(listObj) {
recodedError <- if (!length(listObj) %in% c(1, 3)) {
sprintf("expected list object to be of length 1 (no tolerances) or 3 (with tolerances), not %i", length(listObj))
} else if (!is.numeric(df[[listObj[[1]][1]]])) {
"did not expect tolerances for non-numeric variable"
}
sprintf("%s - %s", listObj[1], recodedError)
}), collapse="\n\t")
)
)
}
# check id_col is a column in df
if (!id_col %in% colnames(df)) stop(sprintf("id_col '%s' not found in df", id_col))
# check target item in id_col
if (!target %in% df[[id_col]]) stop(sprintf("'%s' not found in '%s' column of df", target, id_col))
# get the euclidean distance, and add as a new column, 2nd after the id_col column; all NA if no numeric variables
vars_sans_tols <- sapply(vars, function(x) x[[1]], USE.NAMES = FALSE)
numeric_vars <- vars_sans_tols[sapply(df[, vars_sans_tols, drop = FALSE], is.numeric)]
if (length(numeric_vars) > 0) {
df$euclidean_distance <- LexOPS::euc_dists(df, target = target, vars = numeric_vars, id_col = id_col, standard_eval = TRUE)
} else {
df$euclidean_distance <- NA
}
# reorder rows by euclidean_distance and move id_col and euclidean_distance to front
df <- df[order(df$euclidean_distance), , drop = FALSE]
cols_order <- c(id_col, "euclidean_distance", setdiff(names(df), c(id_col, "euclidean_distance")))
df <- df[, cols_order, drop = FALSE]
# get the numeric and character tolerances relative to the target word
numFilt <- lapply(vars, function(listObj) {
if (is.numeric(df[[listObj[1]]])) {
out <- listObj
match_string_val <- df[[ listObj[[1]] ]][df[[id_col]] == target]
if (length(listObj) == 3) {
out[2:3] <- as.numeric(out[2:3]) + match_string_val
} else if (length(listObj) == 1) {
out[2:3] <- match_string_val
}
return(out)
}
})
numFilt[sapply(numFilt, is.null)] <- NULL # remove NULL values (probably character filters)
charFilt <- lapply(vars, function(listObj) {
if (!is.numeric(df[[listObj[1]]])) {
out <- listObj
out[2] <- as.character(df[[ listObj[[1]] ]][df[[id_col]] == target])
return(out)
}
})
charFilt[sapply(charFilt, is.null)] <- NULL # remove NULL values (probably numeric filters)
# filter out words that don't fit the filters
if (length(numFilt) > 0) {
# build numeric mask
num_mask <- rep(TRUE, nrow(df))
for (filt in numFilt) {
varname <- filt[[1]]
lower <- as.numeric(filt[[2]])
upper <- as.numeric(filt[[3]])
num_mask <- num_mask & (df[[varname]] >= lower & df[[varname]] <= upper)
}
numOut <- df[num_mask, , drop = FALSE]
}
if (length(charFilt) > 0) {
# build character mask
char_mask <- rep(TRUE, nrow(df))
for (filt in charFilt) {
varname <- as.character(filt[1])
val <- as.character(filt[2])
char_mask <- char_mask & (as.character(df[[varname]]) == val)
}
charOut <- df[char_mask, , drop = FALSE]
}
# return the result
if (length(numFilt) > 0 & length(charFilt) > 0) {
# intersection of both masks
both_mask <- (rownames(df) %in% rownames(numOut)) & (rownames(df) %in% rownames(charOut))
out <- df[both_mask, , drop = FALSE]
} else if (length(numFilt) > 0 & length(charFilt) == 0) {
out <- numOut
} else {
out <- charOut
}
# if the filter argument is FALSE, return the original df, but with new column matchFilter
if (!filter) {
df$matchFilter <- df[[id_col]] %in% out[[id_col]]
out <- df[c(id_col, "matchFilter", setdiff(names(df), c(id_col, "matchFilter")))]
}
# remove the target word
out <- out[out[[id_col]] != target, , drop = FALSE]
# return the result
out
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.