blob: 31ba0063806a4aaa0b7ee28f804927acb8b58274 [file] [log] [blame]
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001#' @include logging.R
2setGeneric("collocationAnalysis", function(kco, ...) standardGeneric("collocationAnalysis"))
Marc Kupietzdbd431a2021-08-29 12:17:45 +02003
Marc Kupietz1d400f62026-09-03 14:46:16 +02004#' Keep only collocates that are attested often enough relative to expectation
5#'
6#' Rows without an expected frequency are kept, as are all rows if the ratio is
7#' 0 or `NULL`, which switches the filter off.
8#'
9#' @param result collocation analysis result
10#' @param minObservedExpectedRatio minimum ratio of observed to expected
11#' co-occurrence frequency
12#' @return `result` without the rows that fall below the ratio
13#' @noRd
14filterByObservedExpectedRatio <- function(result, minObservedExpectedRatio) {
15 if (is.null(minObservedExpectedRatio) || is.na(minObservedExpectedRatio) ||
16 minObservedExpectedRatio <= 0 || nrow(result) == 0 ||
17 !all(c("O", "E") %in% names(result))) {
18 return(result)
19 }
20 result[is.na(result$E) | result$O >= minObservedExpectedRatio * result$E, , drop = FALSE]
21}
22
Marc Kupietz37f96072026-09-03 07:18:11 +020023
Marc Kupietzdbd431a2021-08-29 12:17:45 +020024#' Collocation analysis
25#'
Marc Kupietza8c40f42025-06-24 15:49:52 +020026#' @family collocation analysis functions
Marc Kupietzdbd431a2021-08-29 12:17:45 +020027#' @aliases collocationAnalysis
28#'
29#' @description
Marc Kupietzdbd431a2021-08-29 12:17:45 +020030#'
31#' Performs a collocation analysis for the given node (or query)
32#' in the given virtual corpus.
33#'
34#' @details
35#' The collocation analysis is currently implemented on the client side, as some of the
36#' functionality is not yet provided by the KorAP backend. Mainly for this reason
37#' it is very slow (several minutes, up to hours), but on the other hand very flexible.
38#' You can, for example, perform the analysis in arbitrary virtual corpora, use complex node queries,
39#' and look for expression-internal collocates using the focus function (see examples and demo).
40#'
41#' To increase speed at the cost of accuracy and possible false negatives,
42#' you can decrease searchHitsSampleLimit and/or topCollocatesLimit and/or set exactFrequencies to FALSE.
43#'
Marc Kupietze7f0d682025-02-19 10:50:59 +010044#' Note that some outdated non-DeReKo back-ends might not yet support returning tokenized matches (warning issued).
45#' In this case, the client library will fall back to client-side tokenization which might be slightly less accurate.
46#' This might lead to false negatives and to frequencies that differ from corresponding ones acquired via the web
Marc Kupietzdbd431a2021-08-29 12:17:45 +020047#' user interface.
48#'
Marc Kupietzdbd431a2021-08-29 12:17:45 +020049#'
Marc Kupietz67edcb52021-09-20 21:54:24 +020050#' @param lemmatizeNodeQuery if TRUE, node query will be lemmatized, i.e. `x -> [tt/l=x]`
Marc Kupietzdbd431a2021-08-29 12:17:45 +020051#' @param minOccur minimum absolute number of observed co-occurrences to consider a collocate candidate
52#' @param topCollocatesLimit limit analysis to the n most frequent collocates in the search hits sample
53#' @param searchHitsSampleLimit limit the size of the search hits sample
54#' @param stopwords vector of stopwords not to be considered as collocates
Marc Kupietz6bd9cad2024-12-18 15:57:26 +010055#' @param withinSpan KorAP span specification (see <https://korap.ids-mannheim.de/doc/ql/poliqarp-plus?embedded=true#spans>) for collocations to be searched within. Defaults to `base/s=s`.
Marc Kupietzdbd431a2021-08-29 12:17:45 +020056#' @param exactFrequencies if FALSE, extrapolate observed co-occurrence frequencies from frequencies in search hits sample, otherwise retrieve exact co-occurrence frequencies
57#' @param seed seed for random page collecting order
Marc Kupietz67edcb52021-09-20 21:54:24 +020058#' @param expand if TRUE, `node` and `vc` parameters are expanded to all of their combinations
Marc Kupietz7d400e02021-12-19 16:39:36 +010059#' @param maxRecurse apply collocation analysis recursively `maxRecurse` times
60#' @param addExamples If TRUE, examples for instances of collocations will be added in a column `example`. This makes a difference in particular if `node` is given as a lemma query.
Marc Kupietz2b0b0a12025-10-19 14:49:14 +020061#' @param thresholdScore association score function (see \code{\link{association-score-functions}}) to use for computing the threshold that is applied for recursive collocation analysis calls (only applied when \code{maxRecurse > 0})
Marc Kupietzb6416be2026-09-03 14:37:37 +020062#' @param threshold minimum value of `thresholdScore` function call to apply collocation analysis recursively (only applied when \code{maxRecurse > 0}).
63#' Note that the default score, `logDice`, expresses how salient a pair is
64#' rather than how surprising, so that a frequent collocate can pass it while
Marc Kupietz1d400f62026-09-03 14:46:16 +020065#' co-occurring less often than expected. `minObservedExpectedRatio` keeps
66#' those out. See the "Salience versus surprise" section of
67#' \code{\link{association-score-functions}}.
68#' @param minObservedExpectedRatio minimum ratio of observed to expected co-occurrence
69#' frequency a collocate must reach. Defaults to 1, which keeps only collocates
70#' that occur at least as often as expected by chance, corresponding to a
71#' non-negative `pmi`. Without it, frequent words can end up among the top
72#' collocates by `logDice` although the node does not attract them at all (see
73#' the "Salience versus surprise" section of
74#' \code{\link{association-score-functions}}). Raise it to demand a stronger
75#' contrast, e.g. 2 for collocates occurring at least twice as often as
76#' expected, or set it to 0 to switch the filter off and obtain the unfiltered
77#' result of earlier versions, e.g. in order to study repulsion.
Marc Kupietz7d400e02021-12-19 16:39:36 +010078#' @param localStopwords vector of stopwords that will not be considered as collocates in the current function call, but that will not be passed to recursive calls
Marc Kupietz47d0d2b2021-12-19 16:38:52 +010079#' @param collocateFilterRegex allow only collocates matching the regular expression
Marc Kupietzde679ea2025-10-19 13:14:51 +020080#' @param queryMissingScores if TRUE, attempt to retrieve corpus-based association scores for vc/collocate combinations that would otherwise be imputed, by re-querying the KorAP backend without applying the collocate frequency threshold
Marc Kupietz95253342026-08-31 10:18:43 +020081#' @param missingScoreQuantile lower quantile (evaluated per association measure over the pooled result set) that anchors the adaptive floor used for imputing missing scores between virtual corpora; a robust spread is subtracted from this anchor so the imputed values stay at or below the weakest observed scores. Imputed cells are marked in the `imputed*` columns; see the section on interpreting multi-VC comparisons below
Marc Kupietze34a8be2025-10-17 20:13:42 +020082#' @param vcLabel optional label override for the current virtual corpus (used internally when named VC collections are expanded)
Marc Kupietzc902c232026-09-08 07:58:01 +020083#' @param cacheAs path to an RDS file to keep the result in. If the file exists and records the same call, it is read back instead of contacting the server; otherwise the query is run and its result stored there. Unlike the connection's `cache`, this file belongs to the caller, which is what keeps an analysis reproducible once the corpus has grown or the scores have changed. Defaults to \code{NULL} (no file).
Marc Kupietz37f96072026-09-03 07:18:11 +020084#'
85#' The analysis parameters are stored alongside the result. If they differ from
86#' those of the current call, the cached result would not be the one that was
87#' asked for, so it is recomputed and the file overwritten, with a warning
88#' naming the parameters that differ. Pass a different \code{cacheAs} file name
89#' to keep an existing analysis. Cache files written by RKorAPClient 1.3.0 do
90#' not contain the parameters yet and are used as they are.
Marc Kupietz67edcb52021-09-20 21:54:24 +020091#' @param ... more arguments will be passed to [collocationScoreQuery()]
Marc Kupietzdbd431a2021-08-29 12:17:45 +020092#' @inheritParams collocationScoreQuery,KorAPConnection-method
Marc Kupietz130a2a22025-10-18 16:09:23 +020093#' @return
94#' A tibble where each row represents a candidate collocate for the requested node.
95#' Columns include (depending on the selected association measures):
Marc Kupietzdb2fabd2026-04-27 15:01:37 +020096#'
Marc Kupietz130a2a22025-10-18 16:09:23 +020097#' \itemize{
98#' \item \code{node}, \code{collocate}, \code{vc}, \code{label}: identifiers for the query node, collocate, virtual corpus, and optional label.
99#' \item Frequency and contingency information such as \code{frequency}, \code{O}, \code{O1}, \code{O2}, \code{E}, \code{leftContextSize}, \code{rightContextSize}, and \code{w}.
100#' \item Association measures (e.g. \code{logDice}, \code{ll}, \code{mi}, ...), one column per requested scorer.
101#' \item Per-labelled association scores produced by multi-VC comparisons using the pattern \code{<measure>_<label>}.
102#' \item Ranks per label/measure with the pattern \code{rank_<label>_<measure>} (1 is best) and the corresponding percentile ranks \code{percentile_rank_<label>_<measure>}.
103#' \item Pairwise contrasts for two-label comparisons, e.g. \code{delta_<measure>}, \code{delta_rank_<measure>}, and \code{delta_percentile_rank_<measure>}.
Marc Kupietz09b1c082026-05-01 14:45:47 +0200104#' \item Summary columns describing the strongest labels per measure (\code{winner_*}, \code{runner_up_*}, \code{loser_*}, and \code{max_delta_*}), including winner/loser \code{webUIRequestUrl} columns. In multi-VC comparisons, missing per-label concordance URLs are derived from another available row URL for the same \code{node}/\code{collocate} by replacing the \code{cq} parameter with the target label's virtual corpus. Unsuffixed \code{winner_webUIRequestUrl} and \code{loser_webUIRequestUrl} columns are populated only when the score-based URL choices agree.
Marc Kupietzf2e89bf2026-09-09 15:41:35 +0200105#' \item \code{imputed_<label>}: whether the score for that label was imputed rather than observed (see \code{missingScoreQuantile}). \code{n_imputed} counts them, and \code{imputed} is \code{n_imputed > 0}: it describes the node/collocate pair across all labels, not the label of the row it stands in. A row can therefore carry \code{imputed = TRUE} while its own scores are perfectly attested, because the pair is missing from some other virtual corpus - use \code{imputed_<label>} for the row itself. Filter with \code{dplyr::filter(!imputed)} to keep only collocates attested in every compared virtual corpus.
Marc Kupietz130a2a22025-10-18 16:09:23 +0200106#' \item Optional helper columns such as \code{query}, \code{example}, or \code{url} when example retrieval is requested.
107#' }
Marc Kupietz95253342026-08-31 10:18:43 +0200108#' @section Interpreting multi-VC comparisons:
109#'
Marc Kupietzba15cff2026-08-31 10:19:56 +0200110#' `r lifecycle::badge("experimental")`
111#'
112#' The comparison columns produced when `vc` holds more than one virtual corpus
113#' are experimental: their names and semantics may still change in a future
114#' release without a deprecation cycle. Code that has to keep working across
115#' versions should select the columns it needs explicitly.
116#'
117#' They are an exploration aid, not a significance test. When reading them, keep
118#' three properties in mind.
Marc Kupietz95253342026-08-31 10:18:43 +0200119#'
120#' \strong{Imputed scores describe presence/absence, not contrast.} A collocate
121#' that passes the `minOccur` and `topCollocatesLimit` thresholds in one virtual
122#' corpus but not in another has no observed score for the latter. Such cells are
123#' imputed from a floor derived from the pooled result set (see
124#' `missingScoreQuantile`), so the corresponding `delta_*` and `max_delta_*`
125#' values measure the distance to that floor rather than an attested difference.
126#' The `imputed`, `n_imputed` and `imputed_<label>` columns mark these rows;
127#' `dplyr::filter(!imputed)` restricts the result to collocates attested
128#' everywhere, and `queryMissingScores = TRUE` replaces most imputed cells with
Marc Kupietzf2e89bf2026-09-09 15:41:35 +0200129#' scores actually retrieved from the backend. Mind what `imputed` is about: the
130#' pair, not the row. It is `TRUE` as soon as one label lacks the collocate, and
131#' stays `TRUE` on the rows of the labels where it is attested, which is what
132#' makes `dplyr::filter(!imputed)` drop the pair as a whole. Whether the row at
133#' hand rests on an imputed score is what `imputed_<label>` says.
134#'
135#' \strong{Per-label columns carry syntactic names.} The label in
136#' `<measure>_<label>`, `rank_<label>_<measure>` and `imputed_<label>` is the one
137#' the caller gave, put through [make.names()], so that the result stays a well
138#' formed data frame: a virtual corpus named `1976-1980` appears as
139#' `logDice_X1976.1980`. The `label` column and the `winner_*` / `loser_*`
140#' columns keep the name as it was given, so mapping between the two means
141#' applying the same transformation, e.g.
142#' `stats::setNames(make.names(labels), labels)`.
Marc Kupietz95253342026-08-31 10:18:43 +0200143#'
144#' \strong{Imputed values are relative to one analysis.} The floor is computed
145#' from the scores present in the result at hand. Analysing a node on its own and
146#' analysing it together with other nodes therefore yield different imputed
147#' values, and deltas involving imputed cells are not comparable across separate
148#' calls. Deltas between observed scores are unaffected.
149#'
150#' \strong{Winners carry no uncertainty.} Unlike [ci()], which attaches
151#' confidence intervals to relative frequencies, the `winner_*` / `loser_*`
152#' columns simply order point estimates. A collocate wins by a hair on six
153#' occurrences exactly as decisively as one that wins by a wide margin on
154#' thousands. Consult the observed frequencies (`O`, `O1`, `O2`) and the
155#' `webUIRequestUrl` concordance links before drawing conclusions from a
156#' small difference.
157#'
158#' Note also that `rank_<label>_<measure>` and
159#' `percentile_rank_<label>_<measure>` are computed within each label, over that
160#' label's own candidate set. Candidate sets usually differ in size between
161#' virtual corpora, so rank-based deltas compare positions in populations of
162#' different sizes.
Marc Kupietzc4540a22025-10-14 17:39:53 +0200163#' @importFrom dplyr arrange desc slice_head bind_rows group_by mutate ungroup left_join select row_number all_of first
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200164#' @importFrom purrr pmap
Marc Kupietzc4540a22025-10-14 17:39:53 +0200165#' @importFrom tidyr expand_grid pivot_wider
166#' @importFrom rlang sym
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200167#'
168#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200169#' \dontrun{
170#'
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200171#' # Find top collocates of "Packung" inside and outside the sports domain.
172#' KorAPConnection(verbose = TRUE) |>
173#' collocationAnalysis("Packung",
174#' vc = c("textClass=sport", "textClass!=sport"),
175#' leftContextSize = 1, rightContextSize = 1, topCollocatesLimit = 20
176#' ) |>
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200177#' dplyr::filter(logDice >= 5)
178#' }
179#'
Marc Kupietz6ae76052021-09-21 10:34:00 +0200180#' \dontrun{
181#'
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200182#' # Identify the most prominent light verb construction with "in ... setzen".
183#' # Note that, currently, the use of focus function disallows exactFrequencies.
Marc Kupietz4cd066d2025-02-28 15:48:23 +0100184#' KorAPConnection(verbose = TRUE) |>
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200185#' collocationAnalysis("focus(in [tt/p=NN] {[tt/l=setzen]})",
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200186#' leftContextSize = 1, rightContextSize = 0, exactFrequencies = FALSE, topCollocatesLimit = 20
187#' )
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200188#' }
189#'
190#' @export
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200191setMethod(
192 "collocationAnalysis", "KorAPConnection",
193 function(kco,
194 node,
195 vc = "",
196 lemmatizeNodeQuery = FALSE,
197 minOccur = 5,
198 leftContextSize = 5,
199 rightContextSize = 5,
200 topCollocatesLimit = 200,
201 searchHitsSampleLimit = 20000,
202 ignoreCollocateCase = FALSE,
203 withinSpan = ifelse(exactFrequencies, "base/s=s", ""),
204 exactFrequencies = TRUE,
205 stopwords = append(RKorAPClient::synsemanticStopwords(), node),
206 seed = 7,
207 expand = length(vc) != length(node),
208 maxRecurse = 0,
209 addExamples = FALSE,
210 thresholdScore = "logDice",
211 threshold = 2.0,
212 localStopwords = c(),
213 collocateFilterRegex = "^[:alnum:]+-?[:alnum:]*$",
Marc Kupietz1d400f62026-09-03 14:46:16 +0200214 minObservedExpectedRatio = 1,
Marc Kupietzde679ea2025-10-19 13:14:51 +0200215 queryMissingScores = FALSE,
Marc Kupietz9894a372025-10-18 14:51:29 +0200216 missingScoreQuantile = 0.05,
Marc Kupietze34a8be2025-10-17 20:13:42 +0200217 vcLabel = NA_character_,
Marc Kupietzdb2fabd2026-04-27 15:01:37 +0200218 cacheAs = NULL,
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200219 ...) {
Marc Kupietzb2862d42025-10-18 10:17:49 +0200220 word <- frequency <- O <- NULL
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200221
Marc Kupietzc902c232026-09-08 07:58:01 +0200222 cacheRecord <- NULL
Marc Kupietz37f96072026-09-03 07:18:11 +0200223 if (!is.null(cacheAs)) {
Marc Kupietzc902c232026-09-08 07:58:01 +0200224 cacheAs <- cacheAsFileName(cacheAs)
225 cacheRecord <- cacheAsRecord(environment(), list(...), kco)
226 cached <- readCacheAs(cacheAs, kco, cacheRecord, "collocation analysis")
227 if (!is.null(cached)) {
Marc Kupietz37f96072026-09-03 07:18:11 +0200228 return(cached)
229 }
Marc Kupietzdb2fabd2026-04-27 15:01:37 +0200230 }
231
Marc Kupietzb2862d42025-10-18 10:17:49 +0200232 if (!exactFrequencies && (!is.na(withinSpan) && !is.null(withinSpan) && nzchar(withinSpan))) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200233 stop(sprintf("Not empty withinSpan (='%s') requires exactFrequencies=TRUE", withinSpan), call. = FALSE)
234 }
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200235
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200236 warnIfNotAuthorized(kco)
Marc Kupietz581a29b2021-09-04 20:51:04 +0200237
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200238 if (lemmatizeNodeQuery) {
239 node <- lemmatizeWordQuery(node)
240 }
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200241
Marc Kupietze34a8be2025-10-17 20:13:42 +0200242 vcNames <- names(vc)
Marc Kupietze34a8be2025-10-17 20:13:42 +0200243 if (is.null(vcNames)) {
244 vcNames <- rep(NA_character_, length(vc))
Marc Kupietze34a8be2025-10-17 20:13:42 +0200245 }
246
247 label_lookup <- NULL
Marc Kupietzb2862d42025-10-18 10:17:49 +0200248 if (!is.null(names(vc)) && length(vc) > 0) {
249 raw_names <- names(vc)
250 if (any(!is.na(raw_names) & raw_names != "")) {
251 label_lookup <- stats::setNames(raw_names, vc)
252 }
Marc Kupietze34a8be2025-10-17 20:13:42 +0200253 }
254
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200255 result <- if (length(node) > 1 || length(vc) > 1) {
Marc Kupietze34a8be2025-10-17 20:13:42 +0200256 grid <- if (expand) {
Marc Kupietzb2862d42025-10-18 10:17:49 +0200257 tmp_grid <- tidyr::expand_grid(node = node, idx = seq_along(vc))
258 tmp_grid$vc <- vc[tmp_grid$idx]
259 tmp_grid$vcLabel <- vcNames[tmp_grid$idx]
260 tmp_grid[, c("node", "vc", "vcLabel"), drop = FALSE]
Marc Kupietze34a8be2025-10-17 20:13:42 +0200261 } else {
262 tibble(node = node, vc = vc, vcLabel = vcNames)
263 }
264
265 multi_result <- purrr::pmap(grid, function(node, vc, vcLabel, ...) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200266 collocationAnalysis(kco,
267 node = node,
268 vc = vc,
269 minOccur = minOccur,
Marc Kupietz1d400f62026-09-03 14:46:16 +0200270 minObservedExpectedRatio = minObservedExpectedRatio,
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200271 leftContextSize = leftContextSize,
272 rightContextSize = rightContextSize,
273 topCollocatesLimit = topCollocatesLimit,
274 searchHitsSampleLimit = searchHitsSampleLimit,
275 ignoreCollocateCase = ignoreCollocateCase,
276 withinSpan = withinSpan,
277 exactFrequencies = exactFrequencies,
278 stopwords = stopwords,
279 addExamples = TRUE,
280 localStopwords = localStopwords,
281 seed = seed,
282 expand = expand,
Marc Kupietz9894a372025-10-18 14:51:29 +0200283 missingScoreQuantile = missingScoreQuantile,
Marc Kupietzde679ea2025-10-19 13:14:51 +0200284 queryMissingScores = queryMissingScores,
Marc Kupietzb2862d42025-10-18 10:17:49 +0200285 collocateFilterRegex = collocateFilterRegex,
Marc Kupietze34a8be2025-10-17 20:13:42 +0200286 vcLabel = vcLabel,
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200287 ...
288 )
289 }) |>
Marc Kupietze31322e2025-10-17 18:55:36 +0200290 bind_rows()
291
292 if (!"vc" %in% names(multi_result) || nrow(multi_result) == 0) {
293 multi_result
294 } else {
Marc Kupietzde679ea2025-10-19 13:14:51 +0200295 if (queryMissingScores) {
296 multi_result <- backfill_missing_scores(
297 multi_result,
298 grid = grid,
299 kco = kco,
300 ignoreCollocateCase = ignoreCollocateCase,
301 ...
302 )
303 }
304
Marc Kupietze34a8be2025-10-17 20:13:42 +0200305 if (!"label" %in% names(multi_result)) {
306 multi_result$label <- NA_character_
307 }
308
309 if (!is.null(label_lookup)) {
310 override <- unname(label_lookup[multi_result$vc])
311 missing_idx <- is.na(multi_result$label) | multi_result$label == ""
312 if (any(missing_idx)) {
313 multi_result$label[missing_idx] <- override[missing_idx]
314 }
315 }
316
317 missing_idx <- is.na(multi_result$label) | multi_result$label == ""
318 if (any(missing_idx)) {
319 multi_result$label[missing_idx] <- queryStringToLabel(multi_result$vc[missing_idx])
320 }
321
Marc Kupietze31322e2025-10-17 18:55:36 +0200322 multi_result |>
Marc Kupietz9894a372025-10-18 14:51:29 +0200323 add_multi_vc_comparisons(
Marc Kupietz424cb782026-08-31 10:19:29 +0200324 missingScoreQuantile = missingScoreQuantile,
325 verbose = kco@verbose
Marc Kupietz9894a372025-10-18 14:51:29 +0200326 )
Marc Kupietze31322e2025-10-17 18:55:36 +0200327 }
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200328 } else {
Marc Kupietze34a8be2025-10-17 20:13:42 +0200329 if ((is.na(vcLabel) || vcLabel == "") && length(vcNames) >= 1) {
330 vcLabel <- vcNames[1]
331 }
Marc Kupietzb2862d42025-10-18 10:17:49 +0200332
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200333 set.seed(seed)
334 candidates <- collocatesQuery(
335 kco,
336 node,
337 vc = vc,
338 minOccur = minOccur,
339 leftContextSize = leftContextSize,
340 rightContextSize = rightContextSize,
341 searchHitsSampleLimit = searchHitsSampleLimit,
342 ignoreCollocateCase = ignoreCollocateCase,
343 stopwords = append(stopwords, localStopwords),
Marc Kupietzb2862d42025-10-18 10:17:49 +0200344 collocateFilterRegex = collocateFilterRegex,
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200345 ...
346 )
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200347
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200348 if (nrow(candidates) > 0) {
349 candidates <- candidates |>
350 filter(frequency >= minOccur) |>
351 slice_head(n = topCollocatesLimit)
352 collocationScoreQuery(
353 kco,
354 node = node,
355 collocate = candidates$word,
356 vc = vc,
357 leftContextSize = leftContextSize,
358 rightContextSize = rightContextSize,
359 observed = if (exactFrequencies) NA else candidates$frequency,
360 ignoreCollocateCase = ignoreCollocateCase,
361 withinSpan = withinSpan,
362 ...
363 ) |>
364 filter(O >= minOccur) |>
Marc Kupietz1d400f62026-09-03 14:46:16 +0200365 filterByObservedExpectedRatio(minObservedExpectedRatio) |>
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200366 dplyr::arrange(dplyr::desc(logDice))
367 } else {
368 tibble()
369 }
370 }
Marc Kupietzb2862d42025-10-18 10:17:49 +0200371
372 if (!is.na(vcLabel) && vcLabel != "" && "label" %in% names(result)) {
373 result$label <- rep(vcLabel, nrow(result))
374 }
375
376 threshold_col <- thresholdScore
377 if (maxRecurse > 0 && nrow(result) > 0 && threshold_col %in% names(result)) {
378 threshold_values <- result[[threshold_col]]
379 eligible_idx <- which(!is.na(threshold_values) & threshold_values >= threshold)
380 if (length(eligible_idx) > 0) {
381 recurseWith <- result[eligible_idx, , drop = FALSE]
382 result <- collocationAnalysis(
383 kco,
384 node = paste0("(", buildCollocationQuery(
385 removeWithinSpan(recurseWith$node, withinSpan),
386 recurseWith$collocate,
387 leftContextSize = leftContextSize,
388 rightContextSize = rightContextSize,
389 withinSpan = ""
390 ), ")"),
391 vc = vc,
392 minOccur = minOccur,
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200393 leftContextSize = leftContextSize,
394 rightContextSize = rightContextSize,
Marc Kupietzb2862d42025-10-18 10:17:49 +0200395 withinSpan = withinSpan,
396 maxRecurse = maxRecurse - 1,
Marc Kupietz1d400f62026-09-03 14:46:16 +0200397 minObservedExpectedRatio = minObservedExpectedRatio,
Marc Kupietzb2862d42025-10-18 10:17:49 +0200398 stopwords = stopwords,
399 localStopwords = recurseWith$collocate,
400 exactFrequencies = exactFrequencies,
401 searchHitsSampleLimit = searchHitsSampleLimit,
402 topCollocatesLimit = topCollocatesLimit,
403 addExamples = FALSE,
Marc Kupietz9894a372025-10-18 14:51:29 +0200404 missingScoreQuantile = missingScoreQuantile,
Marc Kupietzb2862d42025-10-18 10:17:49 +0200405 collocateFilterRegex = collocateFilterRegex,
Marc Kupietzde679ea2025-10-19 13:14:51 +0200406 queryMissingScores = queryMissingScores,
Marc Kupietz2b0b0a12025-10-19 14:49:14 +0200407 thresholdScore = thresholdScore,
408 threshold = threshold,
Marc Kupietzb2862d42025-10-18 10:17:49 +0200409 vcLabel = vcLabel
410 ) |>
Marc Kupietz2b0b0a12025-10-19 14:49:14 +0200411 bind_rows(result)
412
413 if (threshold_col %in% names(result)) {
414 threshold_values <- result[[threshold_col]]
415 keep_idx <- is.na(threshold_values) | threshold_values >= threshold
416 result <- result[keep_idx, , drop = FALSE]
417 }
418
419 result <- result |>
Marc Kupietzb2862d42025-10-18 10:17:49 +0200420 filter(O >= minOccur) |>
Marc Kupietz1d400f62026-09-03 14:46:16 +0200421 filterByObservedExpectedRatio(minObservedExpectedRatio) |>
Marc Kupietzb2862d42025-10-18 10:17:49 +0200422 dplyr::arrange(dplyr::desc(logDice))
423 }
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200424 }
Marc Kupietzb2862d42025-10-18 10:17:49 +0200425
426 if (addExamples && nrow(result) > 0) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200427 result$query <- buildCollocationQuery(
428 result$node,
429 result$collocate,
430 leftContextSize = leftContextSize,
431 rightContextSize = rightContextSize,
432 withinSpan = withinSpan
433 )
434 result$example <- findExample(
435 kco,
436 query = result$query,
437 vc = result$vc
438 )
439 }
Marc Kupietzb2862d42025-10-18 10:17:49 +0200440
Marc Kupietz0a292632025-10-19 14:04:36 +0200441 if (!is.null(withinSpan) && !is.na(withinSpan) && nzchar(withinSpan) &&
442 nrow(result) > 0 &&
443 "webUIRequestUrl" %in% names(result) &&
444 "query" %in% names(result)) {
445 candidate_rows <- which(!is.na(result$node) &
446 !grepl("focus\\(", result$node, perl = TRUE) &
447 !is.na(result$query) & nzchar(result$query))
448
449 if (length(candidate_rows) > 0) {
450 focused_queries <- vapply(
451 result$query[candidate_rows],
452 inject_focus_into_query,
453 character(1)
454 )
455
456 changed <- focused_queries != result$query[candidate_rows]
457 if (any(changed)) {
458 indices <- candidate_rows[changed]
459 vc_values <- as.character(result$vc)
460 vc_values[is.na(vc_values)] <- ""
461
462 result$webUIRequestUrl[indices] <- mapply(
463 function(new_query, vc_value) {
464 buildWebUIRequestUrlFromString(
465 kco@KorAPUrl,
466 new_query,
467 vc = vc_value,
468 ql = "poliqarp"
469 )
470 },
471 focused_queries[changed],
472 vc_values[indices],
473 USE.NAMES = FALSE
474 )
475 }
476 }
477 }
478
Marc Kupietzdb2fabd2026-04-27 15:01:37 +0200479 if (!is.null(cacheAs)) {
Marc Kupietzc902c232026-09-08 07:58:01 +0200480 writeCacheAs(cacheAs, kco, cacheRecord, "collocation analysis", result)
Marc Kupietzdb2fabd2026-04-27 15:01:37 +0200481 }
482
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200483 result
484 }
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200485)
486
Marc Kupietz76b05592021-12-19 16:26:15 +0100487# #' @export
Marc Kupietz5a336b62021-11-27 17:51:35 +0100488removeWithinSpan <- function(query, withinSpan) {
489 if (withinSpan == "") {
490 return(query)
491 }
492 needle <- sprintf("^\\(contains\\(<%s>, ?(.*)\\){2}$", withinSpan)
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200493 res <- gsub(needle, "\\1", query)
Marc Kupietz5a336b62021-11-27 17:51:35 +0100494 needle <- sprintf("^contains\\(<%s>, ?(.*)\\)$", withinSpan)
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200495 res <- gsub(needle, "\\1", res)
Marc Kupietz5a336b62021-11-27 17:51:35 +0100496 return(res)
497}
498
Marc Kupietzde679ea2025-10-19 13:14:51 +0200499backfill_missing_scores <- function(result,
500 grid,
501 kco,
502 ignoreCollocateCase,
503 ...) {
504 if (!"vc" %in% names(result) || !"node" %in% names(result) || !"collocate" %in% names(result)) {
505 return(result)
506 }
507
508 if (nrow(result) == 0) {
509 return(result)
510 }
511
Marc Kupietz9c53e412026-06-21 12:13:44 +0200512 distinct_pairs <- dplyr::distinct(
513 result,
514 .data$node,
515 .data$collocate
516 )
Marc Kupietzde679ea2025-10-19 13:14:51 +0200517 if (nrow(distinct_pairs) == 0) {
518 return(result)
519 }
520
521 collocates_by_node <- split(as.character(distinct_pairs$collocate), distinct_pairs$node)
522 if (length(collocates_by_node) == 0) {
523 return(result)
524 }
525
526 required_combinations <- unique(as.data.frame(grid[, c("node", "vc", "vcLabel")], drop = FALSE))
527 for (i in seq_len(nrow(required_combinations))) {
528 node_value <- required_combinations$node[i]
529 vc_value <- required_combinations$vc[i]
530
531 collocate_pool <- collocates_by_node[[node_value]]
532 if (is.null(collocate_pool) || length(collocate_pool) == 0) {
533 next
534 }
535
536 existing_idx <- result$node == node_value & result$vc == vc_value
537 existing_collocates <- unique(as.character(result$collocate[existing_idx]))
538 missing_collocates <- setdiff(unique(collocate_pool), existing_collocates)
539 missing_collocates <- missing_collocates[!is.na(missing_collocates) & nzchar(missing_collocates)]
540
541 if (length(missing_collocates) == 0) {
542 next
543 }
544
545 context_rows <- result[result$node == node_value & result$vc == vc_value, , drop = FALSE]
546 if (nrow(context_rows) == 0) {
547 context_rows <- result[result$node == node_value, , drop = FALSE]
548 }
549
550 left_size <- context_rows$leftContextSize[!is.na(context_rows$leftContextSize)][1]
551 if (is.na(left_size) || length(left_size) == 0) {
552 left_size <- result$leftContextSize[!is.na(result$leftContextSize)][1]
553 }
554 if (is.na(left_size) || length(left_size) == 0) {
555 left_size <- 5
556 }
557
558 right_size <- context_rows$rightContextSize[!is.na(context_rows$rightContextSize)][1]
559 if (is.na(right_size) || length(right_size) == 0) {
560 right_size <- result$rightContextSize[!is.na(result$rightContextSize)][1]
561 }
562 if (is.na(right_size) || length(right_size) == 0) {
563 right_size <- 5
564 }
565
566 within_span_value <- ""
567 if ("query" %in% names(context_rows)) {
568 query_candidate <- context_rows$query[!is.na(context_rows$query) & nzchar(context_rows$query)][1]
569 if (!is.na(query_candidate) && nzchar(query_candidate)) {
570 match_one <- regexec("^\\(*contains\\(<([^>]+)>,", query_candidate)
571 matches <- regmatches(query_candidate, match_one)
572 if (length(matches) >= 1 && length(matches[[1]]) >= 2) {
573 within_span_value <- matches[[1]][2]
574 }
575 }
576 }
577
578 new_rows <- collocationScoreQuery(
579 kco,
580 node = node_value,
581 collocate = missing_collocates,
582 vc = vc_value,
583 leftContextSize = left_size,
584 rightContextSize = right_size,
585 ignoreCollocateCase = ignoreCollocateCase,
586 withinSpan = within_span_value,
587 ...
588 )
589
590 if (nrow(new_rows) == 0) {
591 next
592 }
593
594 if (!is.null(required_combinations$vcLabel[i]) && !is.na(required_combinations$vcLabel[i]) && required_combinations$vcLabel[i] != "" && "label" %in% names(new_rows)) {
595 new_rows$label <- required_combinations$vcLabel[i]
596 }
597
598 result <- dplyr::bind_rows(result, new_rows)
599 }
600
601 result
602}
603
Marc Kupietz0a292632025-10-19 14:04:36 +0200604inject_focus_into_query <- function(query) {
605 if (is.null(query) || is.na(query)) {
606 return(query)
607 }
608
609 trimmed <- trimws(query)
610 if (!nzchar(trimmed)) {
611 return(query)
612 }
613
614 if (!grepl("^contains\\(<[^>]+>", trimmed, perl = TRUE)) {
615 return(query)
616 }
617
618 if (grepl("focus\\(", trimmed, perl = TRUE)) {
619 return(query)
620 }
621
622 pattern <- "^contains\\(<([^>]+)>\\s*,\\s*\\((.*)\\)\\)\\s*$"
623 matches <- regexec(pattern, trimmed, perl = TRUE)
624 components <- regmatches(trimmed, matches)
625 if (length(components) == 0 || length(components[[1]]) < 3) {
626 return(query)
627 }
628
629 span <- components[[1]][2]
630 inner <- components[[1]][3]
631 parts <- strsplit(inner, "\\|", perl = TRUE)[[1]]
632 parts <- trimws(parts)
633 parts <- parts[nzchar(parts)]
634
635 if (length(parts) == 0) {
636 return(query)
637 }
638
639 focused <- paste0("focus({", parts, "})")
640 combined <- paste(focused, collapse = " | ")
641
642 sprintf("contains(<%s>, (%s))", span, combined)
643}
644
Marc Kupietz424cb782026-08-31 10:19:29 +0200645add_multi_vc_comparisons <- function(result, missingScoreQuantile = 0.05, verbose = FALSE) {
Marc Kupietz09b1c082026-05-01 14:45:47 +0200646 label <- node <- collocate <- vc <- webUIRequestUrl <- NULL
Marc Kupietzc4540a22025-10-14 17:39:53 +0200647
648 if (!"label" %in% names(result) || dplyr::n_distinct(result$label) < 2) {
649 return(result)
650 }
651
652 numeric_cols <- names(result)[vapply(result, is.numeric, logical(1))]
653 non_score_cols <- c("N", "O", "O1", "O2", "E", "w", "leftContextSize", "rightContextSize", "frequency")
654 score_cols <- setdiff(numeric_cols, non_score_cols)
655
656 if (length(score_cols) == 0) {
657 return(result)
658 }
659
Marc Kupietz9894a372025-10-18 14:51:29 +0200660 compute_score_floor <- function(values) {
Marc Kupietz4cbb5472025-10-19 12:15:25 +0200661 # Estimate a conservative floor so missing scores can be imputed without favoring any label
Marc Kupietz9894a372025-10-18 14:51:29 +0200662 finite_values <- values[is.finite(values)]
663 if (length(finite_values) == 0) {
664 return(0)
665 }
666
667 prob <- min(max(missingScoreQuantile, 0), 0.5)
Marc Kupietz4cbb5472025-10-19 12:15:25 +0200668 # Use a lower quantile as the anchor to stay near the weakest attested scores
Marc Kupietz9894a372025-10-18 14:51:29 +0200669 q_val <- suppressWarnings(stats::quantile(finite_values,
670 probs = prob,
671 names = FALSE,
672 type = 7
673 ))
674
675 if (!is.finite(q_val)) {
676 q_val <- suppressWarnings(min(finite_values, na.rm = TRUE))
677 }
678
679 min_val <- suppressWarnings(min(finite_values, na.rm = TRUE))
680 if (!is.finite(min_val)) {
681 min_val <- 0
682 }
683
684 spread_candidates <- c(
685 suppressWarnings(stats::IQR(finite_values, na.rm = TRUE, type = 7)),
686 stats::sd(finite_values, na.rm = TRUE),
687 abs(q_val) * 0.1,
688 abs(min_val - q_val)
689 )
690 spread_candidates <- spread_candidates[is.finite(spread_candidates)]
691
692 spread <- 0
693 if (length(spread_candidates) > 0) {
694 spread <- max(spread_candidates)
695 }
696 if (!is.finite(spread) || spread == 0) {
697 spread <- max(abs(q_val), abs(min_val), 1e-06)
698 }
699
Marc Kupietz4cbb5472025-10-19 12:15:25 +0200700 # Step away from the anchor by a robust spread estimate to avoid ties with real scores
Marc Kupietz9894a372025-10-18 14:51:29 +0200701 candidate <- q_val - spread
702 if (!is.finite(candidate)) {
703 candidate <- min_val
704 }
705
706 floor_value <- suppressWarnings(min(c(candidate, min_val), na.rm = TRUE))
707 if (!is.finite(floor_value)) {
708 floor_value <- min_val
709 }
710 if (!is.finite(floor_value)) {
711 floor_value <- 0
712 }
713
714 floor_value
715 }
716
717 score_replacements <- stats::setNames(
718 vapply(score_cols, function(col) {
719 compute_score_floor(result[[col]])
720 }, numeric(1)),
721 score_cols
722 )
723
Marc Kupietz7b7a73b2026-08-31 10:31:27 +0200724 # The pivots below keep only the first row per node/collocate/label. Duplicates do occur
725 # legitimately (e.g. the same collocate found at several context positions), but silently
726 # discarding all but one of them would misrepresent the comparison, so say so.
727 comparison_keys <- paste(result$node, result$collocate, result$label, sep = "\r")
728 duplicate_keys <- unique(comparison_keys[duplicated(comparison_keys)])
729 if (length(duplicate_keys) > 0) {
730 warning(
731 sprintf(
732 paste0(
733 "%d node/collocate/label combination(s) occur more than once; only the first row ",
734 "of each is used for the multi-VC comparison columns. Consider ",
735 "mergeDuplicateCollocates() to combine context positions before comparing."
736 ),
737 length(duplicate_keys)
738 ),
739 call. = FALSE
740 )
741 }
742
Marc Kupietzc4540a22025-10-14 17:39:53 +0200743 comparison <- result |>
Marc Kupietz28a29842025-10-18 12:25:09 +0200744 dplyr::select(node, collocate, label, dplyr::all_of(score_cols)) |>
745 tidyr::pivot_wider(
Marc Kupietzc4540a22025-10-14 17:39:53 +0200746 names_from = label,
Marc Kupietz28a29842025-10-18 12:25:09 +0200747 values_from = dplyr::all_of(score_cols),
Marc Kupietzc4540a22025-10-14 17:39:53 +0200748 names_glue = "{.value}_{make.names(label)}",
749 values_fn = dplyr::first
750 )
751
Marc Kupietz5e35d7a2025-10-17 21:21:22 +0200752 raw_labels <- unique(result$label)
753 labels <- make.names(raw_labels)
754 label_map <- stats::setNames(raw_labels, labels)
Marc Kupietz09b1c082026-05-01 14:45:47 +0200755 vc_map <- result |>
756 dplyr::select(label, vc) |>
757 dplyr::filter(!is.na(label), label != "") |>
758 dplyr::distinct(label, .keep_all = TRUE)
759 vc_map <- stats::setNames(vc_map$vc, make.names(vc_map$label))
760
761 replace_web_ui_cq <- function(url, vc_value) {
762 if (length(url) == 0 || is.na(url) || url == "") {
763 return(NA_character_)
764 }
765 if (length(vc_value) == 0 || is.na(vc_value)) {
766 vc_value <- ""
767 }
768 encoded_vc <- urltools::url_encode(enc2utf8(as.character(vc_value)))
769 if (grepl("([?&]cq=)[^&]*", url, perl = TRUE)) {
770 return(sub("([?&]cq=)[^&]*", paste0("\\1", encoded_vc), url, perl = TRUE))
771 }
772 if (encoded_vc == "") {
773 return(url)
774 }
775 paste0(url, ifelse(grepl("\\?", url), "&", "?"), "cq=", encoded_vc)
776 }
777
778 if ("webUIRequestUrl" %in% names(result)) {
779 url_data <- result |>
780 dplyr::select(node, collocate, label, webUIRequestUrl) |>
781 tidyr::pivot_wider(
782 names_from = label,
783 values_from = webUIRequestUrl,
784 names_glue = "webUIRequestUrl_{make.names(label)}",
785 values_fn = dplyr::first
786 )
787
788 comparison <- dplyr::left_join(comparison, url_data, by = c("node", "collocate"))
789
790 url_cols <- paste0("webUIRequestUrl_", labels)
791 present_url_cols <- intersect(url_cols, names(comparison))
792 fallback_urls <- vapply(seq_len(nrow(comparison)), function(i) {
793 urls <- unlist(comparison[i, present_url_cols, drop = FALSE], use.names = FALSE)
794 urls <- as.character(urls)
795 urls <- urls[!is.na(urls) & urls != ""]
796 if (length(urls) == 0) {
797 NA_character_
798 } else {
799 urls[1]
800 }
801 }, character(1))
802
803 for (safe_label in labels) {
804 url_col <- paste0("webUIRequestUrl_", safe_label)
805 if (!url_col %in% names(comparison)) {
806 comparison[[url_col]] <- NA_character_
807 }
808 missing_urls <- is.na(comparison[[url_col]]) | comparison[[url_col]] == ""
809 if (any(missing_urls)) {
810 comparison[[url_col]][missing_urls] <- vapply(
811 fallback_urls[missing_urls],
812 replace_web_ui_cq,
813 character(1),
814 vc_value = vc_map[[safe_label]]
815 )
816 }
817 }
818 }
Marc Kupietzc4540a22025-10-14 17:39:53 +0200819
Marc Kupietz28a29842025-10-18 12:25:09 +0200820 rank_data <- result |>
821 dplyr::distinct(node, collocate)
822
823 for (i in seq_along(raw_labels)) {
824 raw_lab <- raw_labels[i]
825 safe_lab <- labels[i]
826 label_df <- result[result$label == raw_lab, c("node", "collocate", score_cols), drop = FALSE]
827 if (nrow(label_df) == 0) {
828 next
829 }
830 label_df <- dplyr::distinct(label_df)
831 rank_tbl <- label_df[, c("node", "collocate"), drop = FALSE]
832 for (col in score_cols) {
833 rank_col_name <- paste0("rank_", safe_lab, "_", col)
Marc Kupietz130a2a22025-10-18 16:09:23 +0200834 percentile_col_name <- paste0("percentile_rank_", safe_lab, "_", col)
Marc Kupietz28a29842025-10-18 12:25:09 +0200835 values <- label_df[[col]]
836 ranks <- rep(NA_real_, length(values))
Marc Kupietz130a2a22025-10-18 16:09:23 +0200837 percentiles <- rep(NA_real_, length(values))
Marc Kupietz28a29842025-10-18 12:25:09 +0200838 valid_idx <- which(!is.na(values))
839 if (length(valid_idx) > 0) {
840 ranks[valid_idx] <- rank(-values[valid_idx], ties.method = "first")
Marc Kupietz130a2a22025-10-18 16:09:23 +0200841 total <- length(valid_idx)
842 percentiles[valid_idx] <- 1 - (ranks[valid_idx] - 1) / total
Marc Kupietz28a29842025-10-18 12:25:09 +0200843 }
844 rank_tbl[[rank_col_name]] <- ranks
Marc Kupietz130a2a22025-10-18 16:09:23 +0200845 rank_tbl[[percentile_col_name]] <- percentiles
Marc Kupietz28a29842025-10-18 12:25:09 +0200846 }
847 rank_data <- dplyr::left_join(rank_data, rank_tbl, by = c("node", "collocate"))
848 }
849
850 comparison <- dplyr::left_join(comparison, rank_data, by = c("node", "collocate"))
851
Marc Kupietzd7bb5cb2026-08-31 10:18:02 +0200852 # Record which label/measure cells are absent *before* any imputation happens below.
853 # Deltas computed from imputed cells reflect presence/absence of the collocate in a
854 # virtual corpus, not a measured contrast, so users need to be able to tell them apart.
855 imputed_flags <- lapply(labels, function(safe_label) {
856 label_score_cols <- intersect(paste0(score_cols, "_", safe_label), names(comparison))
857 if (length(label_score_cols) == 0) {
858 return(rep(FALSE, nrow(comparison)))
859 }
860 Reduce(`|`, lapply(label_score_cols, function(col) is.na(comparison[[col]])))
861 })
862 names(imputed_flags) <- paste0("imputed_", labels)
863
Marc Kupietz28a29842025-10-18 12:25:09 +0200864 rank_replacements <- numeric(0)
865 rank_column_names <- grep("^rank_", names(comparison), value = TRUE)
866 if (length(rank_column_names) > 0) {
867 rank_replacements <- stats::setNames(
868 vapply(rank_column_names, function(col) {
869 col_values <- comparison[[col]]
870 valid_values <- col_values[!is.na(col_values)]
871 if (length(valid_values) == 0) {
872 nrow(comparison) + 1
873 } else {
874 suppressWarnings(max(valid_values, na.rm = TRUE)) + 1
875 }
876 }, numeric(1)),
877 rank_column_names
878 )
879 }
880
Marc Kupietz130a2a22025-10-18 16:09:23 +0200881 percentile_replacements <- numeric(0)
882 percentile_column_names <- grep("^percentile_rank_", names(comparison), value = TRUE)
883 if (length(percentile_column_names) > 0) {
884 percentile_replacements <- stats::setNames(
885 rep(0, length(percentile_column_names)),
886 percentile_column_names
887 )
888 }
889
Marc Kupietz28a29842025-10-18 12:25:09 +0200890 collapse_label_values <- function(indices, safe_labels_vec) {
891 if (length(indices) == 0) {
892 return(NA_character_)
893 }
894 labs <- label_map[safe_labels_vec[indices]]
895 fallback <- safe_labels_vec[indices]
896 labs[is.na(labs) | labs == ""] <- fallback[is.na(labs) | labs == ""]
897 labs <- labs[!is.na(labs) & labs != ""]
898 if (length(labs) == 0) {
899 return(NA_character_)
900 }
901 paste(unique(labs), collapse = ", ")
902 }
903
Marc Kupietz09b1c082026-05-01 14:45:47 +0200904 collapse_url_values <- function(indices, url_values) {
905 if (length(indices) == 0 || is.null(url_values)) {
906 return(NA_character_)
907 }
908 urls <- as.character(url_values[indices])
909 urls <- urls[!is.na(urls) & urls != ""]
910 if (length(urls) == 0) {
911 return(NA_character_)
912 }
913 paste(unique(urls), collapse = ", ")
914 }
915
Marc Kupietzc4540a22025-10-14 17:39:53 +0200916 if (length(labels) == 2) {
Marc Kupietz9894a372025-10-18 14:51:29 +0200917 fill_scores <- function(x, y, measure_col) {
918 replacement <- score_replacements[[measure_col]]
919 fallback_min <- suppressWarnings(min(c(x, y), na.rm = TRUE))
920 if (!is.finite(fallback_min)) {
921 fallback_min <- 0
Marc Kupietzc4540a22025-10-14 17:39:53 +0200922 }
Marc Kupietz9894a372025-10-18 14:51:29 +0200923 if (!is.null(replacement) && is.finite(replacement)) {
924 replacement <- min(replacement, fallback_min)
925 } else {
926 replacement <- fallback_min
927 }
928 if (!is.finite(replacement)) {
929 replacement <- 0
930 }
931 if (any(is.na(x))) {
932 x[is.na(x)] <- replacement
933 }
934 if (any(is.na(y))) {
935 y[is.na(y)] <- replacement
936 }
Marc Kupietzc4540a22025-10-14 17:39:53 +0200937 list(x = x, y = y)
938 }
939
Marc Kupietz130a2a22025-10-18 16:09:23 +0200940 fill_percentiles <- function(x, y, left_pct_col, right_pct_col) {
941 replacement_left <- percentile_replacements[[left_pct_col]]
942 if (is.null(replacement_left) || !is.finite(replacement_left)) {
943 replacement_left <- 0
944 }
945 replacement_right <- percentile_replacements[[right_pct_col]]
946 if (is.null(replacement_right) || !is.finite(replacement_right)) {
947 replacement_right <- 0
948 }
949 if (any(is.na(x))) {
950 x[is.na(x)] <- replacement_left
951 }
952 if (any(is.na(y))) {
953 y[is.na(y)] <- replacement_right
954 }
955 list(x = x, y = y)
956 }
957
Marc Kupietz28a29842025-10-18 12:25:09 +0200958 fill_ranks <- function(x, y, left_rank_col, right_rank_col) {
959 fallback <- nrow(comparison) + 1
960 replacement_left <- rank_replacements[[left_rank_col]]
961 if (is.null(replacement_left) || !is.finite(replacement_left)) {
962 replacement_left <- fallback
Marc Kupietzc4540a22025-10-14 17:39:53 +0200963 }
Marc Kupietz28a29842025-10-18 12:25:09 +0200964 replacement_right <- rank_replacements[[right_rank_col]]
965 if (is.null(replacement_right) || !is.finite(replacement_right)) {
966 replacement_right <- fallback
967 }
968 if (any(is.na(x))) {
969 x[is.na(x)] <- replacement_left
970 }
971 if (any(is.na(y))) {
972 y[is.na(y)] <- replacement_right
973 }
Marc Kupietzc4540a22025-10-14 17:39:53 +0200974 list(x = x, y = y)
975 }
976
977 left_label <- labels[1]
978 right_label <- labels[2]
979
980 for (col in score_cols) {
981 left_col <- paste0(col, "_", left_label)
982 right_col <- paste0(col, "_", right_label)
983 if (!all(c(left_col, right_col) %in% names(comparison))) {
984 next
985 }
Marc Kupietzdb2fabd2026-04-27 15:01:37 +0200986 filled <- fill_scores(comparison[[left_col]], comparison[[right_col]], col)
Marc Kupietz5e35d7a2025-10-17 21:21:22 +0200987 comparison[[left_col]] <- filled$x
988 comparison[[right_col]] <- filled$y
Marc Kupietzc4540a22025-10-14 17:39:53 +0200989 comparison[[paste0("delta_", col)]] <- filled$x - filled$y
Marc Kupietz28a29842025-10-18 12:25:09 +0200990 rank_left <- paste0("rank_", left_label, "_", col)
991 rank_right <- paste0("rank_", right_label, "_", col)
992 if (all(c(rank_left, rank_right) %in% names(comparison))) {
993 filled_rank <- fill_ranks(
994 comparison[[rank_left]],
995 comparison[[rank_right]],
996 rank_left,
997 rank_right
998 )
999 comparison[[paste0("delta_rank_", col)]] <- filled_rank$x - filled_rank$y
1000 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001001 pct_left <- paste0("percentile_rank_", left_label, "_", col)
1002 pct_right <- paste0("percentile_rank_", right_label, "_", col)
1003 if (all(c(pct_left, pct_right) %in% names(comparison))) {
1004 filled_pct <- fill_percentiles(
1005 comparison[[pct_left]],
1006 comparison[[pct_right]],
1007 pct_left,
1008 pct_right
1009 )
1010 comparison[[paste0("delta_percentile_rank_", col)]] <- filled_pct$x - filled_pct$y
1011 }
Marc Kupietzc4540a22025-10-14 17:39:53 +02001012 }
1013 }
1014
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001015 for (col in score_cols) {
1016 value_cols <- paste0(col, "_", labels)
1017 existing <- value_cols %in% names(comparison)
1018 if (!any(existing)) {
1019 next
1020 }
1021 value_cols <- value_cols[existing]
1022 safe_labels <- labels[existing]
1023
1024 score_values <- comparison[, value_cols, drop = FALSE]
1025
1026 winner_label_col <- paste0("winner_", col)
1027 winner_value_col <- paste0("winner_", col, "_value")
Marc Kupietz09b1c082026-05-01 14:45:47 +02001028 winner_url_col <- paste0("winner_", col, "_webUIRequestUrl")
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001029 runner_label_col <- paste0("runner_up_", col)
1030 runner_value_col <- paste0("runner_up_", col, "_value")
Marc Kupietzb2862d42025-10-18 10:17:49 +02001031 loser_label_col <- paste0("loser_", col)
1032 loser_value_col <- paste0("loser_", col, "_value")
Marc Kupietz09b1c082026-05-01 14:45:47 +02001033 loser_url_col <- paste0("loser_", col, "_webUIRequestUrl")
Marc Kupietzb2862d42025-10-18 10:17:49 +02001034 max_delta_col <- paste0("max_delta_", col)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001035 url_cols <- paste0("webUIRequestUrl_", safe_labels)
1036 has_urls <- all(url_cols %in% names(comparison))
1037 url_values <- if (has_urls) comparison[, url_cols, drop = FALSE] else NULL
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001038
1039 if (nrow(score_values) == 0) {
1040 comparison[[winner_label_col]] <- character(0)
1041 comparison[[winner_value_col]] <- numeric(0)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001042 if (has_urls) {
1043 comparison[[winner_url_col]] <- character(0)
1044 }
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001045 comparison[[runner_label_col]] <- character(0)
1046 comparison[[runner_value_col]] <- numeric(0)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001047 comparison[[loser_label_col]] <- character(0)
1048 comparison[[loser_value_col]] <- numeric(0)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001049 if (has_urls) {
1050 comparison[[loser_url_col]] <- character(0)
1051 }
Marc Kupietzb2862d42025-10-18 10:17:49 +02001052 comparison[[max_delta_col]] <- numeric(0)
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001053 next
1054 }
1055
1056 score_matrix <- as.matrix(score_values)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001057 storage.mode(score_matrix) <- "numeric"
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001058
Marc Kupietzb2862d42025-10-18 10:17:49 +02001059 n_rows <- nrow(score_matrix)
1060 winner_labels <- rep(NA_character_, n_rows)
1061 winner_values <- rep(NA_real_, n_rows)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001062 winner_urls <- rep(NA_character_, n_rows)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001063 runner_labels <- rep(NA_character_, n_rows)
1064 runner_values <- rep(NA_real_, n_rows)
1065 loser_labels <- rep(NA_character_, n_rows)
1066 loser_values <- rep(NA_real_, n_rows)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001067 loser_urls <- rep(NA_character_, n_rows)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001068 max_deltas <- rep(NA_real_, n_rows)
1069
Marc Kupietzb2862d42025-10-18 10:17:49 +02001070 if (n_rows > 0) {
1071 for (i in seq_len(n_rows)) {
1072 numeric_row <- as.numeric(score_matrix[i, ])
1073 if (all(is.na(numeric_row))) {
1074 next
1075 }
1076
Marc Kupietz9894a372025-10-18 14:51:29 +02001077 replacement <- score_replacements[[col]]
1078 fallback_min <- suppressWarnings(min(numeric_row, na.rm = TRUE))
1079 if (!is.finite(fallback_min)) {
1080 fallback_min <- 0
Marc Kupietzb2862d42025-10-18 10:17:49 +02001081 }
Marc Kupietz9894a372025-10-18 14:51:29 +02001082 if (!is.null(replacement) && is.finite(replacement)) {
1083 replacement <- min(replacement, fallback_min)
1084 } else {
1085 replacement <- fallback_min
1086 }
1087 if (!is.finite(replacement)) {
1088 replacement <- 0
1089 }
1090 if (any(is.na(numeric_row))) {
1091 numeric_row[is.na(numeric_row)] <- replacement
1092 }
Marc Kupietzb2862d42025-10-18 10:17:49 +02001093 score_matrix[i, ] <- numeric_row
1094
1095 max_val <- suppressWarnings(max(numeric_row, na.rm = TRUE))
1096 max_idx <- which(numeric_row == max_val)
Marc Kupietz28a29842025-10-18 12:25:09 +02001097 winner_labels[i] <- collapse_label_values(max_idx, safe_labels)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001098 winner_values[i] <- max_val
Marc Kupietz09b1c082026-05-01 14:45:47 +02001099 if (has_urls) {
1100 winner_urls[i] <- collapse_url_values(max_idx, url_values[i, ])
1101 }
Marc Kupietzb2862d42025-10-18 10:17:49 +02001102
1103 unique_vals <- sort(unique(numeric_row), decreasing = TRUE)
1104 if (length(unique_vals) >= 2) {
1105 runner_val <- unique_vals[2]
1106 runner_idx <- which(numeric_row == runner_val)
Marc Kupietz28a29842025-10-18 12:25:09 +02001107 runner_labels[i] <- collapse_label_values(runner_idx, safe_labels)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001108 runner_values[i] <- runner_val
1109 }
1110
1111 min_val <- suppressWarnings(min(numeric_row, na.rm = TRUE))
1112 min_idx <- which(numeric_row == min_val)
Marc Kupietz28a29842025-10-18 12:25:09 +02001113 loser_labels[i] <- collapse_label_values(min_idx, safe_labels)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001114 loser_values[i] <- min_val
Marc Kupietz09b1c082026-05-01 14:45:47 +02001115 if (has_urls) {
1116 loser_urls[i] <- collapse_url_values(min_idx, url_values[i, ])
1117 }
Marc Kupietzb2862d42025-10-18 10:17:49 +02001118
1119 if (is.finite(max_val) && is.finite(min_val)) {
1120 max_deltas[i] <- max_val - min_val
1121 }
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001122 }
Marc Kupietzb2862d42025-10-18 10:17:49 +02001123 }
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001124
Marc Kupietzb2862d42025-10-18 10:17:49 +02001125 comparison[, value_cols] <- score_matrix
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001126 comparison[[winner_label_col]] <- winner_labels
1127 comparison[[winner_value_col]] <- winner_values
Marc Kupietz09b1c082026-05-01 14:45:47 +02001128 if (has_urls) {
1129 comparison[[winner_url_col]] <- winner_urls
1130 }
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001131 comparison[[runner_label_col]] <- runner_labels
1132 comparison[[runner_value_col]] <- runner_values
Marc Kupietzb2862d42025-10-18 10:17:49 +02001133 comparison[[loser_label_col]] <- loser_labels
1134 comparison[[loser_value_col]] <- loser_values
Marc Kupietz09b1c082026-05-01 14:45:47 +02001135 if (has_urls) {
1136 comparison[[loser_url_col]] <- loser_urls
1137 }
Marc Kupietzb2862d42025-10-18 10:17:49 +02001138 comparison[[max_delta_col]] <- max_deltas
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001139 }
1140
Marc Kupietz28a29842025-10-18 12:25:09 +02001141 for (col in score_cols) {
1142 rank_cols <- paste0("rank_", labels, "_", col)
1143 existing <- rank_cols %in% names(comparison)
1144 if (!any(existing)) {
1145 next
1146 }
1147 rank_cols <- rank_cols[existing]
1148 safe_labels <- labels[existing]
1149 rank_values <- comparison[, rank_cols, drop = FALSE]
1150
1151 winner_rank_label_col <- paste0("winner_rank_", col)
1152 winner_rank_value_col <- paste0("winner_rank_", col, "_value")
Marc Kupietz09b1c082026-05-01 14:45:47 +02001153 winner_rank_url_col <- paste0("winner_rank_", col, "_webUIRequestUrl")
Marc Kupietz28a29842025-10-18 12:25:09 +02001154 runner_rank_label_col <- paste0("runner_up_rank_", col)
1155 runner_rank_value_col <- paste0("runner_up_rank_", col, "_value")
1156 loser_rank_label_col <- paste0("loser_rank_", col)
1157 loser_rank_value_col <- paste0("loser_rank_", col, "_value")
Marc Kupietz09b1c082026-05-01 14:45:47 +02001158 loser_rank_url_col <- paste0("loser_rank_", col, "_webUIRequestUrl")
Marc Kupietz28a29842025-10-18 12:25:09 +02001159 max_delta_rank_col <- paste0("max_delta_rank_", col)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001160 url_cols <- paste0("webUIRequestUrl_", safe_labels)
1161 has_urls <- all(url_cols %in% names(comparison))
1162 url_values <- if (has_urls) comparison[, url_cols, drop = FALSE] else NULL
Marc Kupietz28a29842025-10-18 12:25:09 +02001163
1164 if (nrow(rank_values) == 0) {
1165 comparison[[winner_rank_label_col]] <- character(0)
1166 comparison[[winner_rank_value_col]] <- numeric(0)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001167 if (has_urls) {
1168 comparison[[winner_rank_url_col]] <- character(0)
1169 }
Marc Kupietz28a29842025-10-18 12:25:09 +02001170 comparison[[runner_rank_label_col]] <- character(0)
1171 comparison[[runner_rank_value_col]] <- numeric(0)
1172 comparison[[loser_rank_label_col]] <- character(0)
1173 comparison[[loser_rank_value_col]] <- numeric(0)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001174 if (has_urls) {
1175 comparison[[loser_rank_url_col]] <- character(0)
1176 }
Marc Kupietz28a29842025-10-18 12:25:09 +02001177 comparison[[max_delta_rank_col]] <- numeric(0)
1178 next
1179 }
1180
Marc Kupietzdb2fabd2026-04-27 15:01:37 +02001181 rank_matrix <- as.matrix(rank_values)
1182 storage.mode(rank_matrix) <- "numeric"
Marc Kupietz28a29842025-10-18 12:25:09 +02001183
1184 n_rows <- nrow(rank_matrix)
1185 winner_labels <- rep(NA_character_, n_rows)
1186 winner_values <- rep(NA_real_, n_rows)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001187 winner_urls <- rep(NA_character_, n_rows)
Marc Kupietz28a29842025-10-18 12:25:09 +02001188 runner_labels <- rep(NA_character_, n_rows)
1189 runner_values <- rep(NA_real_, n_rows)
1190 loser_labels <- rep(NA_character_, n_rows)
1191 loser_values <- rep(NA_real_, n_rows)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001192 loser_urls <- rep(NA_character_, n_rows)
Marc Kupietz28a29842025-10-18 12:25:09 +02001193 max_deltas <- rep(NA_real_, n_rows)
1194
1195 for (i in seq_len(n_rows)) {
1196 numeric_row <- as.numeric(rank_matrix[i, ])
1197 if (all(is.na(numeric_row))) {
1198 next
1199 }
1200
1201 if (length(rank_cols) > 0) {
1202 replacement_vec <- rank_replacements[rank_cols]
1203 replacement_vec[is.na(replacement_vec)] <- nrow(comparison) + 1
1204 missing_idx <- which(is.na(numeric_row))
1205 if (length(missing_idx) > 0) {
1206 numeric_row[missing_idx] <- replacement_vec[missing_idx]
1207 }
1208 }
1209
1210 valid_idx <- seq_along(numeric_row)
1211 valid_values <- numeric_row[valid_idx]
1212 min_val <- suppressWarnings(min(valid_values, na.rm = TRUE))
1213 min_positions <- valid_idx[which(valid_values == min_val)]
1214 winner_labels[i] <- collapse_label_values(min_positions, safe_labels)
1215 winner_values[i] <- min_val
Marc Kupietz09b1c082026-05-01 14:45:47 +02001216 if (has_urls) {
1217 winner_urls[i] <- collapse_url_values(min_positions, url_values[i, ])
1218 }
Marc Kupietz28a29842025-10-18 12:25:09 +02001219
1220 ordered_vals <- sort(unique(valid_values), decreasing = FALSE)
1221 if (length(ordered_vals) >= 2) {
1222 runner_val <- ordered_vals[2]
1223 runner_positions <- valid_idx[which(valid_values == runner_val)]
1224 runner_labels[i] <- collapse_label_values(runner_positions, safe_labels)
1225 runner_values[i] <- runner_val
1226 }
1227
1228 max_val <- suppressWarnings(max(valid_values, na.rm = TRUE))
1229 max_positions <- valid_idx[which(valid_values == max_val)]
1230 loser_labels[i] <- collapse_label_values(max_positions, safe_labels)
1231 loser_values[i] <- max_val
Marc Kupietz09b1c082026-05-01 14:45:47 +02001232 if (has_urls) {
1233 loser_urls[i] <- collapse_url_values(max_positions, url_values[i, ])
1234 }
Marc Kupietz28a29842025-10-18 12:25:09 +02001235
1236 if (is.finite(max_val) && is.finite(min_val)) {
1237 max_deltas[i] <- max_val - min_val
1238 }
1239 }
1240
1241 comparison[[winner_rank_label_col]] <- winner_labels
1242 comparison[[winner_rank_value_col]] <- winner_values
Marc Kupietz09b1c082026-05-01 14:45:47 +02001243 if (has_urls) {
1244 comparison[[winner_rank_url_col]] <- winner_urls
1245 }
Marc Kupietz28a29842025-10-18 12:25:09 +02001246 comparison[[runner_rank_label_col]] <- runner_labels
1247 comparison[[runner_rank_value_col]] <- runner_values
1248 comparison[[loser_rank_label_col]] <- loser_labels
1249 comparison[[loser_rank_value_col]] <- loser_values
Marc Kupietz09b1c082026-05-01 14:45:47 +02001250 if (has_urls) {
1251 comparison[[loser_rank_url_col]] <- loser_urls
1252 }
Marc Kupietz28a29842025-10-18 12:25:09 +02001253 comparison[[max_delta_rank_col]] <- max_deltas
1254 }
1255
Marc Kupietz130a2a22025-10-18 16:09:23 +02001256 for (col in score_cols) {
1257 pct_cols <- paste0("percentile_rank_", labels, "_", col)
1258 existing <- pct_cols %in% names(comparison)
1259 if (!any(existing)) {
1260 next
1261 }
1262 pct_cols <- pct_cols[existing]
1263 safe_labels <- labels[existing]
1264 pct_values <- comparison[, pct_cols, drop = FALSE]
1265
1266 winner_pct_label_col <- paste0("winner_percentile_rank_", col)
1267 winner_pct_value_col <- paste0("winner_percentile_rank_", col, "_value")
Marc Kupietz09b1c082026-05-01 14:45:47 +02001268 winner_pct_url_col <- paste0("winner_percentile_rank_", col, "_webUIRequestUrl")
Marc Kupietz130a2a22025-10-18 16:09:23 +02001269 runner_pct_label_col <- paste0("runner_up_percentile_rank_", col)
1270 runner_pct_value_col <- paste0("runner_up_percentile_rank_", col, "_value")
1271 loser_pct_label_col <- paste0("loser_percentile_rank_", col)
1272 loser_pct_value_col <- paste0("loser_percentile_rank_", col, "_value")
Marc Kupietz09b1c082026-05-01 14:45:47 +02001273 loser_pct_url_col <- paste0("loser_percentile_rank_", col, "_webUIRequestUrl")
Marc Kupietz130a2a22025-10-18 16:09:23 +02001274 max_delta_pct_col <- paste0("max_delta_percentile_rank_", col)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001275 url_cols <- paste0("webUIRequestUrl_", safe_labels)
1276 has_urls <- all(url_cols %in% names(comparison))
1277 url_values <- if (has_urls) comparison[, url_cols, drop = FALSE] else NULL
Marc Kupietz130a2a22025-10-18 16:09:23 +02001278
1279 if (nrow(pct_values) == 0) {
1280 comparison[[winner_pct_label_col]] <- character(0)
1281 comparison[[winner_pct_value_col]] <- numeric(0)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001282 if (has_urls) {
1283 comparison[[winner_pct_url_col]] <- character(0)
1284 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001285 comparison[[runner_pct_label_col]] <- character(0)
1286 comparison[[runner_pct_value_col]] <- numeric(0)
1287 comparison[[loser_pct_label_col]] <- character(0)
1288 comparison[[loser_pct_value_col]] <- numeric(0)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001289 if (has_urls) {
1290 comparison[[loser_pct_url_col]] <- character(0)
1291 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001292 comparison[[max_delta_pct_col]] <- numeric(0)
1293 next
1294 }
1295
1296 pct_matrix <- as.matrix(pct_values)
1297 storage.mode(pct_matrix) <- "numeric"
1298
1299 n_rows <- nrow(pct_matrix)
1300 winner_labels <- rep(NA_character_, n_rows)
1301 winner_values <- rep(NA_real_, n_rows)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001302 winner_urls <- rep(NA_character_, n_rows)
Marc Kupietz130a2a22025-10-18 16:09:23 +02001303 runner_labels <- rep(NA_character_, n_rows)
1304 runner_values <- rep(NA_real_, n_rows)
1305 loser_labels <- rep(NA_character_, n_rows)
1306 loser_values <- rep(NA_real_, n_rows)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001307 loser_urls <- rep(NA_character_, n_rows)
Marc Kupietz130a2a22025-10-18 16:09:23 +02001308 max_deltas <- rep(NA_real_, n_rows)
1309
1310 if (n_rows > 0) {
1311 for (i in seq_len(n_rows)) {
1312 numeric_row <- as.numeric(pct_matrix[i, ])
1313 if (all(is.na(numeric_row))) {
1314 next
1315 }
1316
1317 if (any(is.na(numeric_row))) {
1318 numeric_row[is.na(numeric_row)] <- 0
1319 }
1320 pct_matrix[i, ] <- numeric_row
1321
1322 max_val <- suppressWarnings(max(numeric_row, na.rm = TRUE))
1323 max_idx <- which(numeric_row == max_val)
1324 winner_labels[i] <- collapse_label_values(max_idx, safe_labels)
1325 winner_values[i] <- max_val
Marc Kupietz09b1c082026-05-01 14:45:47 +02001326 if (has_urls) {
1327 winner_urls[i] <- collapse_url_values(max_idx, url_values[i, ])
1328 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001329
1330 unique_vals <- sort(unique(numeric_row), decreasing = TRUE)
1331 if (length(unique_vals) >= 2) {
1332 runner_val <- unique_vals[2]
1333 runner_idx <- which(numeric_row == runner_val)
1334 runner_labels[i] <- collapse_label_values(runner_idx, safe_labels)
1335 runner_values[i] <- runner_val
1336 }
1337
1338 min_val <- suppressWarnings(min(numeric_row, na.rm = TRUE))
1339 min_idx <- which(numeric_row == min_val)
1340 loser_labels[i] <- collapse_label_values(min_idx, safe_labels)
1341 loser_values[i] <- min_val
Marc Kupietz09b1c082026-05-01 14:45:47 +02001342 if (has_urls) {
1343 loser_urls[i] <- collapse_url_values(min_idx, url_values[i, ])
1344 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001345
1346 if (is.finite(max_val) && is.finite(min_val)) {
1347 max_deltas[i] <- max_val - min_val
1348 }
1349 }
1350 }
1351
1352 comparison[, pct_cols] <- pct_matrix
1353 comparison[[winner_pct_label_col]] <- winner_labels
1354 comparison[[winner_pct_value_col]] <- winner_values
Marc Kupietz09b1c082026-05-01 14:45:47 +02001355 if (has_urls) {
1356 comparison[[winner_pct_url_col]] <- winner_urls
1357 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001358 comparison[[runner_pct_label_col]] <- runner_labels
1359 comparison[[runner_pct_value_col]] <- runner_values
1360 comparison[[loser_pct_label_col]] <- loser_labels
1361 comparison[[loser_pct_value_col]] <- loser_values
Marc Kupietz09b1c082026-05-01 14:45:47 +02001362 if (has_urls) {
1363 comparison[[loser_pct_url_col]] <- loser_urls
1364 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001365 comparison[[max_delta_pct_col]] <- max_deltas
1366 }
1367
Marc Kupietzd7bb5cb2026-08-31 10:18:02 +02001368 for (flag_col in names(imputed_flags)) {
1369 comparison[[flag_col]] <- imputed_flags[[flag_col]]
1370 }
1371 if (length(imputed_flags) > 0) {
1372 comparison$n_imputed <- as.integer(Reduce(`+`, lapply(imputed_flags, as.integer)))
1373 } else {
1374 comparison$n_imputed <- rep(0L, nrow(comparison))
1375 }
1376 comparison$imputed <- comparison$n_imputed > 0L
1377
Marc Kupietz424cb782026-08-31 10:19:29 +02001378 n_imputed_rows <- sum(comparison$imputed)
1379 if (n_imputed_rows > 0) {
1380 log_info(verbose, sprintf(
1381 paste0(
1382 "Imputed scores for %d of %d node/collocate combinations (%d of %d label cells) ",
1383 "that are not attested in every virtual corpus. Their delta and winner/loser ",
1384 "columns reflect presence vs. absence rather than a measured contrast; see the ",
1385 "`imputed` column and `queryMissingScores`.\n"
1386 ),
1387 n_imputed_rows,
1388 nrow(comparison),
1389 sum(comparison$n_imputed),
1390 nrow(comparison) * length(labels)
1391 ))
1392 }
1393
Marc Kupietz09b1c082026-05-01 14:45:47 +02001394 collapse_consensus_url_columns <- function(url_cols) {
1395 if (length(url_cols) == 0) {
1396 return(rep(NA_character_, nrow(comparison)))
1397 }
1398 vapply(seq_len(nrow(comparison)), function(i) {
1399 urls <- unlist(comparison[i, url_cols, drop = FALSE], use.names = FALSE)
1400 urls <- as.character(urls)
1401 urls <- urls[!is.na(urls) & urls != ""]
1402 urls <- unique(urls)
1403 if (length(urls) == 1) {
1404 urls
1405 } else {
1406 NA_character_
1407 }
1408 }, character(1))
1409 }
1410
1411 winner_score_url_cols <- intersect(paste0("winner_", score_cols, "_webUIRequestUrl"), names(comparison))
1412 loser_score_url_cols <- intersect(paste0("loser_", score_cols, "_webUIRequestUrl"), names(comparison))
1413 if (length(winner_score_url_cols) > 0) {
1414 comparison$winner_webUIRequestUrl <- collapse_consensus_url_columns(winner_score_url_cols)
1415 }
1416 if (length(loser_score_url_cols) > 0) {
1417 comparison$loser_webUIRequestUrl <- collapse_consensus_url_columns(loser_score_url_cols)
1418 }
1419
1420 url_helper_cols <- intersect(paste0("webUIRequestUrl_", labels), names(comparison))
1421 if (length(url_helper_cols) > 0) {
1422 comparison <- dplyr::select(comparison, -dplyr::all_of(url_helper_cols))
1423 }
1424
Marc Kupietzc4540a22025-10-14 17:39:53 +02001425 dplyr::left_join(result, comparison, by = c("node", "collocate"))
1426}
1427
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001428#' @importFrom magrittr debug_pipe
Marc Kupietz2b17b212023-08-27 17:47:26 +02001429#' @importFrom stringr str_detect
1430#' @importFrom dplyr as_tibble tibble rename filter anti_join tibble bind_rows case_when
1431#'
1432matches2FreqTable <- function(matches,
1433 index = 0,
1434 minOccur = 5,
1435 leftContextSize = 5,
1436 rightContextSize = 5,
1437 ignoreCollocateCase = FALSE,
1438 stopwords = c(),
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001439 collocateFilterRegex = "^[:alnum:]+-?[:alnum:]*$",
Marc Kupietz2b17b212023-08-27 17:47:26 +02001440 oldTable = data.frame(word = rep(NA, 1), frequency = rep(NA, 1)),
1441 verbose = TRUE) {
1442 word <- NULL # https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check
1443 frequency <- NULL
1444
1445 if (nrow(matches) < 1) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001446 dplyr::tibble(word = c(), frequency = c())
Marc Kupietz2b17b212023-08-27 17:47:26 +02001447 } else if (index == 0) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001448 if (!"tokens" %in% colnames(matches) || !is.list(matches$tokens)) {
Marc Kupietz2b17b212023-08-27 17:47:26 +02001449 log_info(verbose, "Outdated KorAP server: Falling back to client side tokenization.\n")
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001450 return(snippet2FreqTable(matches$snippet, minOccur, leftContextSize, rightContextSize,
1451 ignoreCollocateCase = ignoreCollocateCase,
1452 stopwords = stopwords, oldTable = oldTable, verbose = verbose
1453 ))
Marc Kupietz2b17b212023-08-27 17:47:26 +02001454 }
1455 log_info(verbose, paste("Joining", nrow(matches), "kwics\n"))
Marc Kupietza25fbd92025-10-14 17:38:09 +02001456 for (i in seq_len(nrow(matches))) {
Marc Kupietz2b17b212023-08-27 17:47:26 +02001457 oldTable <- matches2FreqTable(
1458 matches,
1459 i,
1460 leftContextSize = leftContextSize,
1461 rightContextSize = rightContextSize,
1462 collocateFilterRegex = collocateFilterRegex,
1463 oldTable = oldTable,
1464 stopwords = stopwords
1465 )
1466 }
1467 log_info(verbose, paste("Aggregating", length(oldTable$word), "tokens\n"))
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001468 oldTable |>
Marc Kupietz4cd066d2025-02-28 15:48:23 +01001469 group_by(word) |>
1470 mutate(word = dplyr::case_when(ignoreCollocateCase ~ tolower(word), TRUE ~ word)) |>
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001471 summarise(frequency = sum(frequency), .groups = "drop") |>
Marc Kupietz2b17b212023-08-27 17:47:26 +02001472 arrange(desc(frequency))
1473 } else {
Marc Kupietz7cf697f2026-09-05 10:47:53 +02001474 # as.character keeps the column when stopwords is empty: tibble(word = c())
1475 # would drop it altogether and the anti_join below would not find it
1476 stopwordsTable <- dplyr::tibble(word = as.character(stopwords))
Marc Kupietz2b17b212023-08-27 17:47:26 +02001477
1478 left <- tail(unlist(matches$tokens$left[index]), leftContextSize)
1479
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001480 # cat(paste("left:", left, "\n", collapse=" "))
Marc Kupietz2b17b212023-08-27 17:47:26 +02001481
1482 right <- head(unlist(matches$tokens$right[index]), rightContextSize)
1483
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001484 # cat(paste("right:", right, "\n", collapse=" "))
Marc Kupietz2b17b212023-08-27 17:47:26 +02001485
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001486 if (length(left) + length(right) == 0) {
Marc Kupietz2b17b212023-08-27 17:47:26 +02001487 oldTable
1488 } else {
Marc Kupietz4cd066d2025-02-28 15:48:23 +01001489 table(c(left, right)) |>
1490 dplyr::as_tibble(.name_repair = "minimal") |>
1491 dplyr::rename(word = 1, frequency = 2) |>
1492 dplyr::filter(str_detect(word, collocateFilterRegex)) |>
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001493 dplyr::anti_join(stopwordsTable, by = "word") |>
Marc Kupietz2b17b212023-08-27 17:47:26 +02001494 dplyr::bind_rows(oldTable)
1495 }
1496 }
1497}
1498
Marc Kupietz7cf697f2026-09-05 10:47:53 +02001499#' Text content of a KWIC snippet span
1500#'
1501#' Returns the text inside the span captured by `pattern`, with any nested
1502#' markup removed, or `NA` if the snippet does not contain that span at all.
1503#' The capture is greedy on purpose: the context spans contain further spans,
1504#' such as `<span class="more">`, whose closing tag a lazy match would stop at.
1505#'
1506#' @param snippet KWIC snippet
1507#' @param pattern regular expression whose first group captures the span content
1508#' @return text content of the span, or `NA`
1509#' @noRd
1510htmlSpanContent <- function(snippet, pattern) {
1511 content <- str_match(snippet, pattern)[1, 2]
1512 if (is.na(content)) {
1513 return(NA_character_)
1514 }
1515 stringr::str_trim(stringr::str_replace_all(content, "<[^>]*>", " "))
1516}
1517
Marc Kupietz2b17b212023-08-27 17:47:26 +02001518#' @importFrom magrittr debug_pipe
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001519#' @importFrom stringr str_match str_split str_detect
1520#' @importFrom dplyr as_tibble tibble rename filter anti_join tibble bind_rows case_when
1521#'
1522snippet2FreqTable <- function(snippet,
1523 minOccur = 5,
1524 leftContextSize = 5,
1525 rightContextSize = 5,
1526 ignoreCollocateCase = FALSE,
1527 stopwords = c(),
1528 tokenizeRegex = "([! )(\uc2\uab,.:?\u201e\u201c\'\"]+|&quot;)",
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001529 collocateFilterRegex = "^[:alnum:]+-?[:alnum:]*$",
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001530 oldTable = data.frame(word = rep(NA, 1), frequency = rep(NA, 1)),
1531 verbose = TRUE) {
1532 word <- NULL # https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check
1533 frequency <- NULL
1534
1535 if (length(snippet) < 1) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001536 dplyr::tibble(word = c(), frequency = c())
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001537 } else if (length(snippet) > 1) {
Marc Kupietza47d1502023-04-18 15:26:47 +02001538 log_info(verbose, paste("Joining", length(snippet), "kwics\n"))
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001539 for (s in snippet) {
1540 oldTable <- snippet2FreqTable(
1541 s,
1542 leftContextSize = leftContextSize,
1543 rightContextSize = rightContextSize,
Marc Kupietz47d0d2b2021-12-19 16:38:52 +01001544 collocateFilterRegex = collocateFilterRegex,
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001545 oldTable = oldTable,
1546 stopwords = stopwords
1547 )
1548 }
Marc Kupietza47d1502023-04-18 15:26:47 +02001549 log_info(verbose, paste("Aggregating", length(oldTable$word), "tokens\n"))
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001550 oldTable |>
Marc Kupietz4cd066d2025-02-28 15:48:23 +01001551 group_by(word) |>
1552 mutate(word = dplyr::case_when(ignoreCollocateCase ~ tolower(word), TRUE ~ word)) |>
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001553 summarise(frequency = sum(frequency), .groups = "drop") |>
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001554 arrange(desc(frequency))
1555 } else {
Marc Kupietz7cf697f2026-09-05 10:47:53 +02001556 # as.character keeps the column when stopwords is empty: tibble(word = c())
1557 # would drop it altogether and the anti_join below would not find it
1558 stopwordsTable <- dplyr::tibble(word = as.character(stopwords))
1559
1560 # The two context spans are taken one by one, up to the element that follows
1561 # them, and stripped of whatever markup they contain. Matching the snippet
1562 # as a whole used to require one particular shape and silently dropped every
1563 # snippet of any other, which cost about 15% of the hits of a
1564 # contains(<base/s=s>, ...) query: those are cut at the sentence boundary and
1565 # carry a <span class="cutted"> inside the match, and a match filling the
1566 # whole sentence leaves an empty context span (see issue #14).
1567 leftContext <- htmlSpanContent(snippet, '<span class="context-left">(.*)</span><span class="match">')
1568 rightContext <- htmlSpanContent(snippet, '<span class="context-right">(.*)</span>')
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001569
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001570 left <- if (leftContextSize > 0) {
Marc Kupietz7cf697f2026-09-05 10:47:53 +02001571 tail(unlist(str_split(leftContext, tokenizeRegex)), leftContextSize)
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001572 } else {
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001573 ""
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001574 }
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001575
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001576 right <- if (rightContextSize > 0) {
Marc Kupietz7cf697f2026-09-05 10:47:53 +02001577 head(unlist(str_split(rightContext, tokenizeRegex)), rightContextSize)
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001578 } else {
1579 ""
1580 }
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001581
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001582 if (is.na(left[1]) || is.na(right[1]) || length(left) + length(right) == 0) {
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001583 oldTable
1584 } else {
Marc Kupietz4cd066d2025-02-28 15:48:23 +01001585 table(c(left, right)) |>
1586 dplyr::as_tibble(.name_repair = "minimal") |>
1587 dplyr::rename(word = 1, frequency = 2) |>
1588 dplyr::filter(str_detect(word, collocateFilterRegex)) |>
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001589 dplyr::anti_join(stopwordsTable, by = "word") |>
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001590 dplyr::bind_rows(oldTable)
1591 }
1592 }
1593}
1594
1595#' Preliminary synsemantic stopwords function
1596#'
1597#' @description
Marc Kupietz67edcb52021-09-20 21:54:24 +02001598#' `r lifecycle::badge("experimental")`
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001599#'
1600#' Preliminary synsemantic stopwords function to be used in collocation analysis.
1601#'
1602#' @details
1603#' Currently only suitable for German. See stopwords package for other languages.
1604#'
1605#' @param ... future arguments for language detection
1606#'
1607#' @family collocation analysis functions
1608#' @return Vector of synsemantic stopwords.
1609#' @export
1610synsemanticStopwords <- function(...) {
Marc Kupietzc79155b2025-10-19 13:42:55 +02001611 base <- c(
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001612 "der",
1613 "die",
1614 "und",
1615 "in",
1616 "den",
1617 "von",
1618 "mit",
1619 "das",
1620 "zu",
1621 "im",
1622 "ist",
1623 "auf",
1624 "sich",
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001625 "des",
1626 "dem",
1627 "nicht",
1628 "ein",
1629 "eine",
1630 "es",
1631 "auch",
1632 "an",
1633 "als",
1634 "am",
1635 "aus",
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001636 "bei",
1637 "er",
1638 "dass",
1639 "sie",
1640 "nach",
1641 "um",
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001642 "zum",
1643 "noch",
1644 "war",
1645 "einen",
1646 "einer",
1647 "wie",
1648 "einem",
1649 "vor",
1650 "bis",
1651 "\u00fcber",
1652 "so",
1653 "aber",
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001654 "diese",
Marc Kupietzc79155b2025-10-19 13:42:55 +02001655 "oder"
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001656 )
Marc Kupietzc79155b2025-10-19 13:42:55 +02001657
1658 lower <- unique(tolower(base))
1659 capitalized <- paste0(toupper(substr(lower, 1, 1)), substring(lower, 2))
1660
1661 unique(c(lower, capitalized))
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001662}
1663
Marc Kupietz5a336b62021-11-27 17:51:35 +01001664
Marc Kupietz76b05592021-12-19 16:26:15 +01001665# #' @export
Marc Kupietz5a336b62021-11-27 17:51:35 +01001666findExample <-
1667 function(kco,
1668 query,
1669 vc = "",
1670 matchOnly = TRUE) {
1671 out <- character(length = length(query))
1672
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001673 if (length(vc) < length(query)) {
Marc Kupietz5a336b62021-11-27 17:51:35 +01001674 vc <- rep(vc, length(query))
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001675 }
Marc Kupietz5a336b62021-11-27 17:51:35 +01001676
1677 for (i in seq_along(query)) {
1678 q <- corpusQuery(kco, paste0("(", query[i], ")"), vc = vc[i], metadataOnly = FALSE)
Marc Kupietzb811ffb2021-12-07 10:34:10 +01001679 if (q@totalResults > 0) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001680 q <- fetchNext(q, maxFetch = 50, randomizePageOrder = F)
Marc Kupietz7cf697f2026-09-05 10:47:53 +02001681 # A failed request leaves collectedMatches without a snippet column at
1682 # all, so that the example is character(0) rather than NA and assigning
1683 # it fails with "replacement has length zero" (see issue #14).
Marc Kupietzb811ffb2021-12-07 10:34:10 +01001684 example <- as.character((q@collectedMatches)$snippet[1])
Marc Kupietz7cf697f2026-09-05 10:47:53 +02001685 out[i] <- if (length(example) != 1 || is.na(example)) {
1686 ""
1687 } else if (matchOnly) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001688 gsub(".*<mark>(.+)</mark>.*", "\\1", example)
Marc Kupietz5a336b62021-11-27 17:51:35 +01001689 } else {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001690 stringr::str_replace(example, "<[^>]*>", "")
Marc Kupietz5a336b62021-11-27 17:51:35 +01001691 }
Marc Kupietzb811ffb2021-12-07 10:34:10 +01001692 } else {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001693 out[i] <- ""
Marc Kupietzb811ffb2021-12-07 10:34:10 +01001694 }
Marc Kupietz5a336b62021-11-27 17:51:35 +01001695 }
1696 out
1697 }
1698
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001699collocatesQuery <-
1700 function(kco,
1701 query,
1702 vc = "",
1703 minOccur = 5,
1704 leftContextSize = 5,
1705 rightContextSize = 5,
1706 searchHitsSampleLimit = 20000,
1707 ignoreCollocateCase = FALSE,
1708 stopwords = c(),
Marc Kupietzb2862d42025-10-18 10:17:49 +02001709 collocateFilterRegex = "^[:alnum:]+-?[:alnum:]*$",
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001710 ...) {
1711 frequency <- NULL
1712 q <- corpusQuery(kco, query, vc, metadataOnly = F, ...)
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001713 if (q@totalResults == 0) {
1714 tibble(word = c(), frequency = c())
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001715 } else {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001716 q <- fetchNext(q, maxFetch = searchHitsSampleLimit, randomizePageOrder = TRUE)
1717 matches2FreqTable(q@collectedMatches,
1718 0,
1719 minOccur = minOccur,
1720 leftContextSize = leftContextSize,
1721 rightContextSize = rightContextSize,
1722 ignoreCollocateCase = ignoreCollocateCase,
1723 stopwords = stopwords,
Marc Kupietzb2862d42025-10-18 10:17:49 +02001724 collocateFilterRegex = collocateFilterRegex,
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001725 ...,
1726 verbose = kco@verbose
1727 ) |>
Marc Kupietz4cd066d2025-02-28 15:48:23 +01001728 mutate(frequency = frequency * q@totalResults / min(q@totalResults, searchHitsSampleLimit)) |>
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001729 filter(frequency >= minOccur)
1730 }
1731 }