blob: c54b46deaffe49f778dc1f5f27d3d324ad270860 [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 Kupietzd7bb5cb2026-08-31 10:18:02 +0200105#' \item \code{imputed_<label>}, \code{n_imputed}, and \code{imputed}: flags marking rows whose scores were not observed for some label but imputed (see \code{missingScoreQuantile}). 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
129#' scores actually retrieved from the backend.
130#'
131#' \strong{Imputed values are relative to one analysis.} The floor is computed
132#' from the scores present in the result at hand. Analysing a node on its own and
133#' analysing it together with other nodes therefore yield different imputed
134#' values, and deltas involving imputed cells are not comparable across separate
135#' calls. Deltas between observed scores are unaffected.
136#'
137#' \strong{Winners carry no uncertainty.} Unlike [ci()], which attaches
138#' confidence intervals to relative frequencies, the `winner_*` / `loser_*`
139#' columns simply order point estimates. A collocate wins by a hair on six
140#' occurrences exactly as decisively as one that wins by a wide margin on
141#' thousands. Consult the observed frequencies (`O`, `O1`, `O2`) and the
142#' `webUIRequestUrl` concordance links before drawing conclusions from a
143#' small difference.
144#'
145#' Note also that `rank_<label>_<measure>` and
146#' `percentile_rank_<label>_<measure>` are computed within each label, over that
147#' label's own candidate set. Candidate sets usually differ in size between
148#' virtual corpora, so rank-based deltas compare positions in populations of
149#' different sizes.
Marc Kupietzc4540a22025-10-14 17:39:53 +0200150#' @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 +0200151#' @importFrom purrr pmap
Marc Kupietzc4540a22025-10-14 17:39:53 +0200152#' @importFrom tidyr expand_grid pivot_wider
153#' @importFrom rlang sym
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200154#'
155#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200156#' \dontrun{
157#'
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200158#' # Find top collocates of "Packung" inside and outside the sports domain.
159#' KorAPConnection(verbose = TRUE) |>
160#' collocationAnalysis("Packung",
161#' vc = c("textClass=sport", "textClass!=sport"),
162#' leftContextSize = 1, rightContextSize = 1, topCollocatesLimit = 20
163#' ) |>
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200164#' dplyr::filter(logDice >= 5)
165#' }
166#'
Marc Kupietz6ae76052021-09-21 10:34:00 +0200167#' \dontrun{
168#'
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200169#' # Identify the most prominent light verb construction with "in ... setzen".
170#' # Note that, currently, the use of focus function disallows exactFrequencies.
Marc Kupietz4cd066d2025-02-28 15:48:23 +0100171#' KorAPConnection(verbose = TRUE) |>
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200172#' collocationAnalysis("focus(in [tt/p=NN] {[tt/l=setzen]})",
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200173#' leftContextSize = 1, rightContextSize = 0, exactFrequencies = FALSE, topCollocatesLimit = 20
174#' )
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200175#' }
176#'
177#' @export
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200178setMethod(
179 "collocationAnalysis", "KorAPConnection",
180 function(kco,
181 node,
182 vc = "",
183 lemmatizeNodeQuery = FALSE,
184 minOccur = 5,
185 leftContextSize = 5,
186 rightContextSize = 5,
187 topCollocatesLimit = 200,
188 searchHitsSampleLimit = 20000,
189 ignoreCollocateCase = FALSE,
190 withinSpan = ifelse(exactFrequencies, "base/s=s", ""),
191 exactFrequencies = TRUE,
192 stopwords = append(RKorAPClient::synsemanticStopwords(), node),
193 seed = 7,
194 expand = length(vc) != length(node),
195 maxRecurse = 0,
196 addExamples = FALSE,
197 thresholdScore = "logDice",
198 threshold = 2.0,
199 localStopwords = c(),
200 collocateFilterRegex = "^[:alnum:]+-?[:alnum:]*$",
Marc Kupietz1d400f62026-09-03 14:46:16 +0200201 minObservedExpectedRatio = 1,
Marc Kupietzde679ea2025-10-19 13:14:51 +0200202 queryMissingScores = FALSE,
Marc Kupietz9894a372025-10-18 14:51:29 +0200203 missingScoreQuantile = 0.05,
Marc Kupietze34a8be2025-10-17 20:13:42 +0200204 vcLabel = NA_character_,
Marc Kupietzdb2fabd2026-04-27 15:01:37 +0200205 cacheAs = NULL,
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200206 ...) {
Marc Kupietzb2862d42025-10-18 10:17:49 +0200207 word <- frequency <- O <- NULL
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200208
Marc Kupietzc902c232026-09-08 07:58:01 +0200209 cacheRecord <- NULL
Marc Kupietz37f96072026-09-03 07:18:11 +0200210 if (!is.null(cacheAs)) {
Marc Kupietzc902c232026-09-08 07:58:01 +0200211 cacheAs <- cacheAsFileName(cacheAs)
212 cacheRecord <- cacheAsRecord(environment(), list(...), kco)
213 cached <- readCacheAs(cacheAs, kco, cacheRecord, "collocation analysis")
214 if (!is.null(cached)) {
Marc Kupietz37f96072026-09-03 07:18:11 +0200215 return(cached)
216 }
Marc Kupietzdb2fabd2026-04-27 15:01:37 +0200217 }
218
Marc Kupietzb2862d42025-10-18 10:17:49 +0200219 if (!exactFrequencies && (!is.na(withinSpan) && !is.null(withinSpan) && nzchar(withinSpan))) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200220 stop(sprintf("Not empty withinSpan (='%s') requires exactFrequencies=TRUE", withinSpan), call. = FALSE)
221 }
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200222
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200223 warnIfNotAuthorized(kco)
Marc Kupietz581a29b2021-09-04 20:51:04 +0200224
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200225 if (lemmatizeNodeQuery) {
226 node <- lemmatizeWordQuery(node)
227 }
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200228
Marc Kupietze34a8be2025-10-17 20:13:42 +0200229 vcNames <- names(vc)
Marc Kupietze34a8be2025-10-17 20:13:42 +0200230 if (is.null(vcNames)) {
231 vcNames <- rep(NA_character_, length(vc))
Marc Kupietze34a8be2025-10-17 20:13:42 +0200232 }
233
234 label_lookup <- NULL
Marc Kupietzb2862d42025-10-18 10:17:49 +0200235 if (!is.null(names(vc)) && length(vc) > 0) {
236 raw_names <- names(vc)
237 if (any(!is.na(raw_names) & raw_names != "")) {
238 label_lookup <- stats::setNames(raw_names, vc)
239 }
Marc Kupietze34a8be2025-10-17 20:13:42 +0200240 }
241
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200242 result <- if (length(node) > 1 || length(vc) > 1) {
Marc Kupietze34a8be2025-10-17 20:13:42 +0200243 grid <- if (expand) {
Marc Kupietzb2862d42025-10-18 10:17:49 +0200244 tmp_grid <- tidyr::expand_grid(node = node, idx = seq_along(vc))
245 tmp_grid$vc <- vc[tmp_grid$idx]
246 tmp_grid$vcLabel <- vcNames[tmp_grid$idx]
247 tmp_grid[, c("node", "vc", "vcLabel"), drop = FALSE]
Marc Kupietze34a8be2025-10-17 20:13:42 +0200248 } else {
249 tibble(node = node, vc = vc, vcLabel = vcNames)
250 }
251
252 multi_result <- purrr::pmap(grid, function(node, vc, vcLabel, ...) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200253 collocationAnalysis(kco,
254 node = node,
255 vc = vc,
256 minOccur = minOccur,
Marc Kupietz1d400f62026-09-03 14:46:16 +0200257 minObservedExpectedRatio = minObservedExpectedRatio,
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200258 leftContextSize = leftContextSize,
259 rightContextSize = rightContextSize,
260 topCollocatesLimit = topCollocatesLimit,
261 searchHitsSampleLimit = searchHitsSampleLimit,
262 ignoreCollocateCase = ignoreCollocateCase,
263 withinSpan = withinSpan,
264 exactFrequencies = exactFrequencies,
265 stopwords = stopwords,
266 addExamples = TRUE,
267 localStopwords = localStopwords,
268 seed = seed,
269 expand = expand,
Marc Kupietz9894a372025-10-18 14:51:29 +0200270 missingScoreQuantile = missingScoreQuantile,
Marc Kupietzde679ea2025-10-19 13:14:51 +0200271 queryMissingScores = queryMissingScores,
Marc Kupietzb2862d42025-10-18 10:17:49 +0200272 collocateFilterRegex = collocateFilterRegex,
Marc Kupietze34a8be2025-10-17 20:13:42 +0200273 vcLabel = vcLabel,
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200274 ...
275 )
276 }) |>
Marc Kupietze31322e2025-10-17 18:55:36 +0200277 bind_rows()
278
279 if (!"vc" %in% names(multi_result) || nrow(multi_result) == 0) {
280 multi_result
281 } else {
Marc Kupietzde679ea2025-10-19 13:14:51 +0200282 if (queryMissingScores) {
283 multi_result <- backfill_missing_scores(
284 multi_result,
285 grid = grid,
286 kco = kco,
287 ignoreCollocateCase = ignoreCollocateCase,
288 ...
289 )
290 }
291
Marc Kupietze34a8be2025-10-17 20:13:42 +0200292 if (!"label" %in% names(multi_result)) {
293 multi_result$label <- NA_character_
294 }
295
296 if (!is.null(label_lookup)) {
297 override <- unname(label_lookup[multi_result$vc])
298 missing_idx <- is.na(multi_result$label) | multi_result$label == ""
299 if (any(missing_idx)) {
300 multi_result$label[missing_idx] <- override[missing_idx]
301 }
302 }
303
304 missing_idx <- is.na(multi_result$label) | multi_result$label == ""
305 if (any(missing_idx)) {
306 multi_result$label[missing_idx] <- queryStringToLabel(multi_result$vc[missing_idx])
307 }
308
Marc Kupietze31322e2025-10-17 18:55:36 +0200309 multi_result |>
Marc Kupietz9894a372025-10-18 14:51:29 +0200310 add_multi_vc_comparisons(
Marc Kupietz424cb782026-08-31 10:19:29 +0200311 missingScoreQuantile = missingScoreQuantile,
312 verbose = kco@verbose
Marc Kupietz9894a372025-10-18 14:51:29 +0200313 )
Marc Kupietze31322e2025-10-17 18:55:36 +0200314 }
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200315 } else {
Marc Kupietze34a8be2025-10-17 20:13:42 +0200316 if ((is.na(vcLabel) || vcLabel == "") && length(vcNames) >= 1) {
317 vcLabel <- vcNames[1]
318 }
Marc Kupietzb2862d42025-10-18 10:17:49 +0200319
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200320 set.seed(seed)
321 candidates <- collocatesQuery(
322 kco,
323 node,
324 vc = vc,
325 minOccur = minOccur,
326 leftContextSize = leftContextSize,
327 rightContextSize = rightContextSize,
328 searchHitsSampleLimit = searchHitsSampleLimit,
329 ignoreCollocateCase = ignoreCollocateCase,
330 stopwords = append(stopwords, localStopwords),
Marc Kupietzb2862d42025-10-18 10:17:49 +0200331 collocateFilterRegex = collocateFilterRegex,
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200332 ...
333 )
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200334
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200335 if (nrow(candidates) > 0) {
336 candidates <- candidates |>
337 filter(frequency >= minOccur) |>
338 slice_head(n = topCollocatesLimit)
339 collocationScoreQuery(
340 kco,
341 node = node,
342 collocate = candidates$word,
343 vc = vc,
344 leftContextSize = leftContextSize,
345 rightContextSize = rightContextSize,
346 observed = if (exactFrequencies) NA else candidates$frequency,
347 ignoreCollocateCase = ignoreCollocateCase,
348 withinSpan = withinSpan,
349 ...
350 ) |>
351 filter(O >= minOccur) |>
Marc Kupietz1d400f62026-09-03 14:46:16 +0200352 filterByObservedExpectedRatio(minObservedExpectedRatio) |>
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200353 dplyr::arrange(dplyr::desc(logDice))
354 } else {
355 tibble()
356 }
357 }
Marc Kupietzb2862d42025-10-18 10:17:49 +0200358
359 if (!is.na(vcLabel) && vcLabel != "" && "label" %in% names(result)) {
360 result$label <- rep(vcLabel, nrow(result))
361 }
362
363 threshold_col <- thresholdScore
364 if (maxRecurse > 0 && nrow(result) > 0 && threshold_col %in% names(result)) {
365 threshold_values <- result[[threshold_col]]
366 eligible_idx <- which(!is.na(threshold_values) & threshold_values >= threshold)
367 if (length(eligible_idx) > 0) {
368 recurseWith <- result[eligible_idx, , drop = FALSE]
369 result <- collocationAnalysis(
370 kco,
371 node = paste0("(", buildCollocationQuery(
372 removeWithinSpan(recurseWith$node, withinSpan),
373 recurseWith$collocate,
374 leftContextSize = leftContextSize,
375 rightContextSize = rightContextSize,
376 withinSpan = ""
377 ), ")"),
378 vc = vc,
379 minOccur = minOccur,
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200380 leftContextSize = leftContextSize,
381 rightContextSize = rightContextSize,
Marc Kupietzb2862d42025-10-18 10:17:49 +0200382 withinSpan = withinSpan,
383 maxRecurse = maxRecurse - 1,
Marc Kupietz1d400f62026-09-03 14:46:16 +0200384 minObservedExpectedRatio = minObservedExpectedRatio,
Marc Kupietzb2862d42025-10-18 10:17:49 +0200385 stopwords = stopwords,
386 localStopwords = recurseWith$collocate,
387 exactFrequencies = exactFrequencies,
388 searchHitsSampleLimit = searchHitsSampleLimit,
389 topCollocatesLimit = topCollocatesLimit,
390 addExamples = FALSE,
Marc Kupietz9894a372025-10-18 14:51:29 +0200391 missingScoreQuantile = missingScoreQuantile,
Marc Kupietzb2862d42025-10-18 10:17:49 +0200392 collocateFilterRegex = collocateFilterRegex,
Marc Kupietzde679ea2025-10-19 13:14:51 +0200393 queryMissingScores = queryMissingScores,
Marc Kupietz2b0b0a12025-10-19 14:49:14 +0200394 thresholdScore = thresholdScore,
395 threshold = threshold,
Marc Kupietzb2862d42025-10-18 10:17:49 +0200396 vcLabel = vcLabel
397 ) |>
Marc Kupietz2b0b0a12025-10-19 14:49:14 +0200398 bind_rows(result)
399
400 if (threshold_col %in% names(result)) {
401 threshold_values <- result[[threshold_col]]
402 keep_idx <- is.na(threshold_values) | threshold_values >= threshold
403 result <- result[keep_idx, , drop = FALSE]
404 }
405
406 result <- result |>
Marc Kupietzb2862d42025-10-18 10:17:49 +0200407 filter(O >= minOccur) |>
Marc Kupietz1d400f62026-09-03 14:46:16 +0200408 filterByObservedExpectedRatio(minObservedExpectedRatio) |>
Marc Kupietzb2862d42025-10-18 10:17:49 +0200409 dplyr::arrange(dplyr::desc(logDice))
410 }
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200411 }
Marc Kupietzb2862d42025-10-18 10:17:49 +0200412
413 if (addExamples && nrow(result) > 0) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200414 result$query <- buildCollocationQuery(
415 result$node,
416 result$collocate,
417 leftContextSize = leftContextSize,
418 rightContextSize = rightContextSize,
419 withinSpan = withinSpan
420 )
421 result$example <- findExample(
422 kco,
423 query = result$query,
424 vc = result$vc
425 )
426 }
Marc Kupietzb2862d42025-10-18 10:17:49 +0200427
Marc Kupietz0a292632025-10-19 14:04:36 +0200428 if (!is.null(withinSpan) && !is.na(withinSpan) && nzchar(withinSpan) &&
429 nrow(result) > 0 &&
430 "webUIRequestUrl" %in% names(result) &&
431 "query" %in% names(result)) {
432 candidate_rows <- which(!is.na(result$node) &
433 !grepl("focus\\(", result$node, perl = TRUE) &
434 !is.na(result$query) & nzchar(result$query))
435
436 if (length(candidate_rows) > 0) {
437 focused_queries <- vapply(
438 result$query[candidate_rows],
439 inject_focus_into_query,
440 character(1)
441 )
442
443 changed <- focused_queries != result$query[candidate_rows]
444 if (any(changed)) {
445 indices <- candidate_rows[changed]
446 vc_values <- as.character(result$vc)
447 vc_values[is.na(vc_values)] <- ""
448
449 result$webUIRequestUrl[indices] <- mapply(
450 function(new_query, vc_value) {
451 buildWebUIRequestUrlFromString(
452 kco@KorAPUrl,
453 new_query,
454 vc = vc_value,
455 ql = "poliqarp"
456 )
457 },
458 focused_queries[changed],
459 vc_values[indices],
460 USE.NAMES = FALSE
461 )
462 }
463 }
464 }
465
Marc Kupietzdb2fabd2026-04-27 15:01:37 +0200466 if (!is.null(cacheAs)) {
Marc Kupietzc902c232026-09-08 07:58:01 +0200467 writeCacheAs(cacheAs, kco, cacheRecord, "collocation analysis", result)
Marc Kupietzdb2fabd2026-04-27 15:01:37 +0200468 }
469
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200470 result
471 }
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200472)
473
Marc Kupietz76b05592021-12-19 16:26:15 +0100474# #' @export
Marc Kupietz5a336b62021-11-27 17:51:35 +0100475removeWithinSpan <- function(query, withinSpan) {
476 if (withinSpan == "") {
477 return(query)
478 }
479 needle <- sprintf("^\\(contains\\(<%s>, ?(.*)\\){2}$", withinSpan)
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200480 res <- gsub(needle, "\\1", query)
Marc Kupietz5a336b62021-11-27 17:51:35 +0100481 needle <- sprintf("^contains\\(<%s>, ?(.*)\\)$", withinSpan)
Marc Kupietz6dfeed92025-06-03 11:58:06 +0200482 res <- gsub(needle, "\\1", res)
Marc Kupietz5a336b62021-11-27 17:51:35 +0100483 return(res)
484}
485
Marc Kupietzde679ea2025-10-19 13:14:51 +0200486backfill_missing_scores <- function(result,
487 grid,
488 kco,
489 ignoreCollocateCase,
490 ...) {
491 if (!"vc" %in% names(result) || !"node" %in% names(result) || !"collocate" %in% names(result)) {
492 return(result)
493 }
494
495 if (nrow(result) == 0) {
496 return(result)
497 }
498
Marc Kupietz9c53e412026-06-21 12:13:44 +0200499 distinct_pairs <- dplyr::distinct(
500 result,
501 .data$node,
502 .data$collocate
503 )
Marc Kupietzde679ea2025-10-19 13:14:51 +0200504 if (nrow(distinct_pairs) == 0) {
505 return(result)
506 }
507
508 collocates_by_node <- split(as.character(distinct_pairs$collocate), distinct_pairs$node)
509 if (length(collocates_by_node) == 0) {
510 return(result)
511 }
512
513 required_combinations <- unique(as.data.frame(grid[, c("node", "vc", "vcLabel")], drop = FALSE))
514 for (i in seq_len(nrow(required_combinations))) {
515 node_value <- required_combinations$node[i]
516 vc_value <- required_combinations$vc[i]
517
518 collocate_pool <- collocates_by_node[[node_value]]
519 if (is.null(collocate_pool) || length(collocate_pool) == 0) {
520 next
521 }
522
523 existing_idx <- result$node == node_value & result$vc == vc_value
524 existing_collocates <- unique(as.character(result$collocate[existing_idx]))
525 missing_collocates <- setdiff(unique(collocate_pool), existing_collocates)
526 missing_collocates <- missing_collocates[!is.na(missing_collocates) & nzchar(missing_collocates)]
527
528 if (length(missing_collocates) == 0) {
529 next
530 }
531
532 context_rows <- result[result$node == node_value & result$vc == vc_value, , drop = FALSE]
533 if (nrow(context_rows) == 0) {
534 context_rows <- result[result$node == node_value, , drop = FALSE]
535 }
536
537 left_size <- context_rows$leftContextSize[!is.na(context_rows$leftContextSize)][1]
538 if (is.na(left_size) || length(left_size) == 0) {
539 left_size <- result$leftContextSize[!is.na(result$leftContextSize)][1]
540 }
541 if (is.na(left_size) || length(left_size) == 0) {
542 left_size <- 5
543 }
544
545 right_size <- context_rows$rightContextSize[!is.na(context_rows$rightContextSize)][1]
546 if (is.na(right_size) || length(right_size) == 0) {
547 right_size <- result$rightContextSize[!is.na(result$rightContextSize)][1]
548 }
549 if (is.na(right_size) || length(right_size) == 0) {
550 right_size <- 5
551 }
552
553 within_span_value <- ""
554 if ("query" %in% names(context_rows)) {
555 query_candidate <- context_rows$query[!is.na(context_rows$query) & nzchar(context_rows$query)][1]
556 if (!is.na(query_candidate) && nzchar(query_candidate)) {
557 match_one <- regexec("^\\(*contains\\(<([^>]+)>,", query_candidate)
558 matches <- regmatches(query_candidate, match_one)
559 if (length(matches) >= 1 && length(matches[[1]]) >= 2) {
560 within_span_value <- matches[[1]][2]
561 }
562 }
563 }
564
565 new_rows <- collocationScoreQuery(
566 kco,
567 node = node_value,
568 collocate = missing_collocates,
569 vc = vc_value,
570 leftContextSize = left_size,
571 rightContextSize = right_size,
572 ignoreCollocateCase = ignoreCollocateCase,
573 withinSpan = within_span_value,
574 ...
575 )
576
577 if (nrow(new_rows) == 0) {
578 next
579 }
580
581 if (!is.null(required_combinations$vcLabel[i]) && !is.na(required_combinations$vcLabel[i]) && required_combinations$vcLabel[i] != "" && "label" %in% names(new_rows)) {
582 new_rows$label <- required_combinations$vcLabel[i]
583 }
584
585 result <- dplyr::bind_rows(result, new_rows)
586 }
587
588 result
589}
590
Marc Kupietz0a292632025-10-19 14:04:36 +0200591inject_focus_into_query <- function(query) {
592 if (is.null(query) || is.na(query)) {
593 return(query)
594 }
595
596 trimmed <- trimws(query)
597 if (!nzchar(trimmed)) {
598 return(query)
599 }
600
601 if (!grepl("^contains\\(<[^>]+>", trimmed, perl = TRUE)) {
602 return(query)
603 }
604
605 if (grepl("focus\\(", trimmed, perl = TRUE)) {
606 return(query)
607 }
608
609 pattern <- "^contains\\(<([^>]+)>\\s*,\\s*\\((.*)\\)\\)\\s*$"
610 matches <- regexec(pattern, trimmed, perl = TRUE)
611 components <- regmatches(trimmed, matches)
612 if (length(components) == 0 || length(components[[1]]) < 3) {
613 return(query)
614 }
615
616 span <- components[[1]][2]
617 inner <- components[[1]][3]
618 parts <- strsplit(inner, "\\|", perl = TRUE)[[1]]
619 parts <- trimws(parts)
620 parts <- parts[nzchar(parts)]
621
622 if (length(parts) == 0) {
623 return(query)
624 }
625
626 focused <- paste0("focus({", parts, "})")
627 combined <- paste(focused, collapse = " | ")
628
629 sprintf("contains(<%s>, (%s))", span, combined)
630}
631
Marc Kupietz424cb782026-08-31 10:19:29 +0200632add_multi_vc_comparisons <- function(result, missingScoreQuantile = 0.05, verbose = FALSE) {
Marc Kupietz09b1c082026-05-01 14:45:47 +0200633 label <- node <- collocate <- vc <- webUIRequestUrl <- NULL
Marc Kupietzc4540a22025-10-14 17:39:53 +0200634
635 if (!"label" %in% names(result) || dplyr::n_distinct(result$label) < 2) {
636 return(result)
637 }
638
639 numeric_cols <- names(result)[vapply(result, is.numeric, logical(1))]
640 non_score_cols <- c("N", "O", "O1", "O2", "E", "w", "leftContextSize", "rightContextSize", "frequency")
641 score_cols <- setdiff(numeric_cols, non_score_cols)
642
643 if (length(score_cols) == 0) {
644 return(result)
645 }
646
Marc Kupietz9894a372025-10-18 14:51:29 +0200647 compute_score_floor <- function(values) {
Marc Kupietz4cbb5472025-10-19 12:15:25 +0200648 # Estimate a conservative floor so missing scores can be imputed without favoring any label
Marc Kupietz9894a372025-10-18 14:51:29 +0200649 finite_values <- values[is.finite(values)]
650 if (length(finite_values) == 0) {
651 return(0)
652 }
653
654 prob <- min(max(missingScoreQuantile, 0), 0.5)
Marc Kupietz4cbb5472025-10-19 12:15:25 +0200655 # Use a lower quantile as the anchor to stay near the weakest attested scores
Marc Kupietz9894a372025-10-18 14:51:29 +0200656 q_val <- suppressWarnings(stats::quantile(finite_values,
657 probs = prob,
658 names = FALSE,
659 type = 7
660 ))
661
662 if (!is.finite(q_val)) {
663 q_val <- suppressWarnings(min(finite_values, na.rm = TRUE))
664 }
665
666 min_val <- suppressWarnings(min(finite_values, na.rm = TRUE))
667 if (!is.finite(min_val)) {
668 min_val <- 0
669 }
670
671 spread_candidates <- c(
672 suppressWarnings(stats::IQR(finite_values, na.rm = TRUE, type = 7)),
673 stats::sd(finite_values, na.rm = TRUE),
674 abs(q_val) * 0.1,
675 abs(min_val - q_val)
676 )
677 spread_candidates <- spread_candidates[is.finite(spread_candidates)]
678
679 spread <- 0
680 if (length(spread_candidates) > 0) {
681 spread <- max(spread_candidates)
682 }
683 if (!is.finite(spread) || spread == 0) {
684 spread <- max(abs(q_val), abs(min_val), 1e-06)
685 }
686
Marc Kupietz4cbb5472025-10-19 12:15:25 +0200687 # Step away from the anchor by a robust spread estimate to avoid ties with real scores
Marc Kupietz9894a372025-10-18 14:51:29 +0200688 candidate <- q_val - spread
689 if (!is.finite(candidate)) {
690 candidate <- min_val
691 }
692
693 floor_value <- suppressWarnings(min(c(candidate, min_val), na.rm = TRUE))
694 if (!is.finite(floor_value)) {
695 floor_value <- min_val
696 }
697 if (!is.finite(floor_value)) {
698 floor_value <- 0
699 }
700
701 floor_value
702 }
703
704 score_replacements <- stats::setNames(
705 vapply(score_cols, function(col) {
706 compute_score_floor(result[[col]])
707 }, numeric(1)),
708 score_cols
709 )
710
Marc Kupietz7b7a73b2026-08-31 10:31:27 +0200711 # The pivots below keep only the first row per node/collocate/label. Duplicates do occur
712 # legitimately (e.g. the same collocate found at several context positions), but silently
713 # discarding all but one of them would misrepresent the comparison, so say so.
714 comparison_keys <- paste(result$node, result$collocate, result$label, sep = "\r")
715 duplicate_keys <- unique(comparison_keys[duplicated(comparison_keys)])
716 if (length(duplicate_keys) > 0) {
717 warning(
718 sprintf(
719 paste0(
720 "%d node/collocate/label combination(s) occur more than once; only the first row ",
721 "of each is used for the multi-VC comparison columns. Consider ",
722 "mergeDuplicateCollocates() to combine context positions before comparing."
723 ),
724 length(duplicate_keys)
725 ),
726 call. = FALSE
727 )
728 }
729
Marc Kupietzc4540a22025-10-14 17:39:53 +0200730 comparison <- result |>
Marc Kupietz28a29842025-10-18 12:25:09 +0200731 dplyr::select(node, collocate, label, dplyr::all_of(score_cols)) |>
732 tidyr::pivot_wider(
Marc Kupietzc4540a22025-10-14 17:39:53 +0200733 names_from = label,
Marc Kupietz28a29842025-10-18 12:25:09 +0200734 values_from = dplyr::all_of(score_cols),
Marc Kupietzc4540a22025-10-14 17:39:53 +0200735 names_glue = "{.value}_{make.names(label)}",
736 values_fn = dplyr::first
737 )
738
Marc Kupietz5e35d7a2025-10-17 21:21:22 +0200739 raw_labels <- unique(result$label)
740 labels <- make.names(raw_labels)
741 label_map <- stats::setNames(raw_labels, labels)
Marc Kupietz09b1c082026-05-01 14:45:47 +0200742 vc_map <- result |>
743 dplyr::select(label, vc) |>
744 dplyr::filter(!is.na(label), label != "") |>
745 dplyr::distinct(label, .keep_all = TRUE)
746 vc_map <- stats::setNames(vc_map$vc, make.names(vc_map$label))
747
748 replace_web_ui_cq <- function(url, vc_value) {
749 if (length(url) == 0 || is.na(url) || url == "") {
750 return(NA_character_)
751 }
752 if (length(vc_value) == 0 || is.na(vc_value)) {
753 vc_value <- ""
754 }
755 encoded_vc <- urltools::url_encode(enc2utf8(as.character(vc_value)))
756 if (grepl("([?&]cq=)[^&]*", url, perl = TRUE)) {
757 return(sub("([?&]cq=)[^&]*", paste0("\\1", encoded_vc), url, perl = TRUE))
758 }
759 if (encoded_vc == "") {
760 return(url)
761 }
762 paste0(url, ifelse(grepl("\\?", url), "&", "?"), "cq=", encoded_vc)
763 }
764
765 if ("webUIRequestUrl" %in% names(result)) {
766 url_data <- result |>
767 dplyr::select(node, collocate, label, webUIRequestUrl) |>
768 tidyr::pivot_wider(
769 names_from = label,
770 values_from = webUIRequestUrl,
771 names_glue = "webUIRequestUrl_{make.names(label)}",
772 values_fn = dplyr::first
773 )
774
775 comparison <- dplyr::left_join(comparison, url_data, by = c("node", "collocate"))
776
777 url_cols <- paste0("webUIRequestUrl_", labels)
778 present_url_cols <- intersect(url_cols, names(comparison))
779 fallback_urls <- vapply(seq_len(nrow(comparison)), function(i) {
780 urls <- unlist(comparison[i, present_url_cols, drop = FALSE], use.names = FALSE)
781 urls <- as.character(urls)
782 urls <- urls[!is.na(urls) & urls != ""]
783 if (length(urls) == 0) {
784 NA_character_
785 } else {
786 urls[1]
787 }
788 }, character(1))
789
790 for (safe_label in labels) {
791 url_col <- paste0("webUIRequestUrl_", safe_label)
792 if (!url_col %in% names(comparison)) {
793 comparison[[url_col]] <- NA_character_
794 }
795 missing_urls <- is.na(comparison[[url_col]]) | comparison[[url_col]] == ""
796 if (any(missing_urls)) {
797 comparison[[url_col]][missing_urls] <- vapply(
798 fallback_urls[missing_urls],
799 replace_web_ui_cq,
800 character(1),
801 vc_value = vc_map[[safe_label]]
802 )
803 }
804 }
805 }
Marc Kupietzc4540a22025-10-14 17:39:53 +0200806
Marc Kupietz28a29842025-10-18 12:25:09 +0200807 rank_data <- result |>
808 dplyr::distinct(node, collocate)
809
810 for (i in seq_along(raw_labels)) {
811 raw_lab <- raw_labels[i]
812 safe_lab <- labels[i]
813 label_df <- result[result$label == raw_lab, c("node", "collocate", score_cols), drop = FALSE]
814 if (nrow(label_df) == 0) {
815 next
816 }
817 label_df <- dplyr::distinct(label_df)
818 rank_tbl <- label_df[, c("node", "collocate"), drop = FALSE]
819 for (col in score_cols) {
820 rank_col_name <- paste0("rank_", safe_lab, "_", col)
Marc Kupietz130a2a22025-10-18 16:09:23 +0200821 percentile_col_name <- paste0("percentile_rank_", safe_lab, "_", col)
Marc Kupietz28a29842025-10-18 12:25:09 +0200822 values <- label_df[[col]]
823 ranks <- rep(NA_real_, length(values))
Marc Kupietz130a2a22025-10-18 16:09:23 +0200824 percentiles <- rep(NA_real_, length(values))
Marc Kupietz28a29842025-10-18 12:25:09 +0200825 valid_idx <- which(!is.na(values))
826 if (length(valid_idx) > 0) {
827 ranks[valid_idx] <- rank(-values[valid_idx], ties.method = "first")
Marc Kupietz130a2a22025-10-18 16:09:23 +0200828 total <- length(valid_idx)
829 percentiles[valid_idx] <- 1 - (ranks[valid_idx] - 1) / total
Marc Kupietz28a29842025-10-18 12:25:09 +0200830 }
831 rank_tbl[[rank_col_name]] <- ranks
Marc Kupietz130a2a22025-10-18 16:09:23 +0200832 rank_tbl[[percentile_col_name]] <- percentiles
Marc Kupietz28a29842025-10-18 12:25:09 +0200833 }
834 rank_data <- dplyr::left_join(rank_data, rank_tbl, by = c("node", "collocate"))
835 }
836
837 comparison <- dplyr::left_join(comparison, rank_data, by = c("node", "collocate"))
838
Marc Kupietzd7bb5cb2026-08-31 10:18:02 +0200839 # Record which label/measure cells are absent *before* any imputation happens below.
840 # Deltas computed from imputed cells reflect presence/absence of the collocate in a
841 # virtual corpus, not a measured contrast, so users need to be able to tell them apart.
842 imputed_flags <- lapply(labels, function(safe_label) {
843 label_score_cols <- intersect(paste0(score_cols, "_", safe_label), names(comparison))
844 if (length(label_score_cols) == 0) {
845 return(rep(FALSE, nrow(comparison)))
846 }
847 Reduce(`|`, lapply(label_score_cols, function(col) is.na(comparison[[col]])))
848 })
849 names(imputed_flags) <- paste0("imputed_", labels)
850
Marc Kupietz28a29842025-10-18 12:25:09 +0200851 rank_replacements <- numeric(0)
852 rank_column_names <- grep("^rank_", names(comparison), value = TRUE)
853 if (length(rank_column_names) > 0) {
854 rank_replacements <- stats::setNames(
855 vapply(rank_column_names, function(col) {
856 col_values <- comparison[[col]]
857 valid_values <- col_values[!is.na(col_values)]
858 if (length(valid_values) == 0) {
859 nrow(comparison) + 1
860 } else {
861 suppressWarnings(max(valid_values, na.rm = TRUE)) + 1
862 }
863 }, numeric(1)),
864 rank_column_names
865 )
866 }
867
Marc Kupietz130a2a22025-10-18 16:09:23 +0200868 percentile_replacements <- numeric(0)
869 percentile_column_names <- grep("^percentile_rank_", names(comparison), value = TRUE)
870 if (length(percentile_column_names) > 0) {
871 percentile_replacements <- stats::setNames(
872 rep(0, length(percentile_column_names)),
873 percentile_column_names
874 )
875 }
876
Marc Kupietz28a29842025-10-18 12:25:09 +0200877 collapse_label_values <- function(indices, safe_labels_vec) {
878 if (length(indices) == 0) {
879 return(NA_character_)
880 }
881 labs <- label_map[safe_labels_vec[indices]]
882 fallback <- safe_labels_vec[indices]
883 labs[is.na(labs) | labs == ""] <- fallback[is.na(labs) | labs == ""]
884 labs <- labs[!is.na(labs) & labs != ""]
885 if (length(labs) == 0) {
886 return(NA_character_)
887 }
888 paste(unique(labs), collapse = ", ")
889 }
890
Marc Kupietz09b1c082026-05-01 14:45:47 +0200891 collapse_url_values <- function(indices, url_values) {
892 if (length(indices) == 0 || is.null(url_values)) {
893 return(NA_character_)
894 }
895 urls <- as.character(url_values[indices])
896 urls <- urls[!is.na(urls) & urls != ""]
897 if (length(urls) == 0) {
898 return(NA_character_)
899 }
900 paste(unique(urls), collapse = ", ")
901 }
902
Marc Kupietzc4540a22025-10-14 17:39:53 +0200903 if (length(labels) == 2) {
Marc Kupietz9894a372025-10-18 14:51:29 +0200904 fill_scores <- function(x, y, measure_col) {
905 replacement <- score_replacements[[measure_col]]
906 fallback_min <- suppressWarnings(min(c(x, y), na.rm = TRUE))
907 if (!is.finite(fallback_min)) {
908 fallback_min <- 0
Marc Kupietzc4540a22025-10-14 17:39:53 +0200909 }
Marc Kupietz9894a372025-10-18 14:51:29 +0200910 if (!is.null(replacement) && is.finite(replacement)) {
911 replacement <- min(replacement, fallback_min)
912 } else {
913 replacement <- fallback_min
914 }
915 if (!is.finite(replacement)) {
916 replacement <- 0
917 }
918 if (any(is.na(x))) {
919 x[is.na(x)] <- replacement
920 }
921 if (any(is.na(y))) {
922 y[is.na(y)] <- replacement
923 }
Marc Kupietzc4540a22025-10-14 17:39:53 +0200924 list(x = x, y = y)
925 }
926
Marc Kupietz130a2a22025-10-18 16:09:23 +0200927 fill_percentiles <- function(x, y, left_pct_col, right_pct_col) {
928 replacement_left <- percentile_replacements[[left_pct_col]]
929 if (is.null(replacement_left) || !is.finite(replacement_left)) {
930 replacement_left <- 0
931 }
932 replacement_right <- percentile_replacements[[right_pct_col]]
933 if (is.null(replacement_right) || !is.finite(replacement_right)) {
934 replacement_right <- 0
935 }
936 if (any(is.na(x))) {
937 x[is.na(x)] <- replacement_left
938 }
939 if (any(is.na(y))) {
940 y[is.na(y)] <- replacement_right
941 }
942 list(x = x, y = y)
943 }
944
Marc Kupietz28a29842025-10-18 12:25:09 +0200945 fill_ranks <- function(x, y, left_rank_col, right_rank_col) {
946 fallback <- nrow(comparison) + 1
947 replacement_left <- rank_replacements[[left_rank_col]]
948 if (is.null(replacement_left) || !is.finite(replacement_left)) {
949 replacement_left <- fallback
Marc Kupietzc4540a22025-10-14 17:39:53 +0200950 }
Marc Kupietz28a29842025-10-18 12:25:09 +0200951 replacement_right <- rank_replacements[[right_rank_col]]
952 if (is.null(replacement_right) || !is.finite(replacement_right)) {
953 replacement_right <- fallback
954 }
955 if (any(is.na(x))) {
956 x[is.na(x)] <- replacement_left
957 }
958 if (any(is.na(y))) {
959 y[is.na(y)] <- replacement_right
960 }
Marc Kupietzc4540a22025-10-14 17:39:53 +0200961 list(x = x, y = y)
962 }
963
964 left_label <- labels[1]
965 right_label <- labels[2]
966
967 for (col in score_cols) {
968 left_col <- paste0(col, "_", left_label)
969 right_col <- paste0(col, "_", right_label)
970 if (!all(c(left_col, right_col) %in% names(comparison))) {
971 next
972 }
Marc Kupietzdb2fabd2026-04-27 15:01:37 +0200973 filled <- fill_scores(comparison[[left_col]], comparison[[right_col]], col)
Marc Kupietz5e35d7a2025-10-17 21:21:22 +0200974 comparison[[left_col]] <- filled$x
975 comparison[[right_col]] <- filled$y
Marc Kupietzc4540a22025-10-14 17:39:53 +0200976 comparison[[paste0("delta_", col)]] <- filled$x - filled$y
Marc Kupietz28a29842025-10-18 12:25:09 +0200977 rank_left <- paste0("rank_", left_label, "_", col)
978 rank_right <- paste0("rank_", right_label, "_", col)
979 if (all(c(rank_left, rank_right) %in% names(comparison))) {
980 filled_rank <- fill_ranks(
981 comparison[[rank_left]],
982 comparison[[rank_right]],
983 rank_left,
984 rank_right
985 )
986 comparison[[paste0("delta_rank_", col)]] <- filled_rank$x - filled_rank$y
987 }
Marc Kupietz130a2a22025-10-18 16:09:23 +0200988 pct_left <- paste0("percentile_rank_", left_label, "_", col)
989 pct_right <- paste0("percentile_rank_", right_label, "_", col)
990 if (all(c(pct_left, pct_right) %in% names(comparison))) {
991 filled_pct <- fill_percentiles(
992 comparison[[pct_left]],
993 comparison[[pct_right]],
994 pct_left,
995 pct_right
996 )
997 comparison[[paste0("delta_percentile_rank_", col)]] <- filled_pct$x - filled_pct$y
998 }
Marc Kupietzc4540a22025-10-14 17:39:53 +0200999 }
1000 }
1001
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001002 for (col in score_cols) {
1003 value_cols <- paste0(col, "_", labels)
1004 existing <- value_cols %in% names(comparison)
1005 if (!any(existing)) {
1006 next
1007 }
1008 value_cols <- value_cols[existing]
1009 safe_labels <- labels[existing]
1010
1011 score_values <- comparison[, value_cols, drop = FALSE]
1012
1013 winner_label_col <- paste0("winner_", col)
1014 winner_value_col <- paste0("winner_", col, "_value")
Marc Kupietz09b1c082026-05-01 14:45:47 +02001015 winner_url_col <- paste0("winner_", col, "_webUIRequestUrl")
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001016 runner_label_col <- paste0("runner_up_", col)
1017 runner_value_col <- paste0("runner_up_", col, "_value")
Marc Kupietzb2862d42025-10-18 10:17:49 +02001018 loser_label_col <- paste0("loser_", col)
1019 loser_value_col <- paste0("loser_", col, "_value")
Marc Kupietz09b1c082026-05-01 14:45:47 +02001020 loser_url_col <- paste0("loser_", col, "_webUIRequestUrl")
Marc Kupietzb2862d42025-10-18 10:17:49 +02001021 max_delta_col <- paste0("max_delta_", col)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001022 url_cols <- paste0("webUIRequestUrl_", safe_labels)
1023 has_urls <- all(url_cols %in% names(comparison))
1024 url_values <- if (has_urls) comparison[, url_cols, drop = FALSE] else NULL
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001025
1026 if (nrow(score_values) == 0) {
1027 comparison[[winner_label_col]] <- character(0)
1028 comparison[[winner_value_col]] <- numeric(0)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001029 if (has_urls) {
1030 comparison[[winner_url_col]] <- character(0)
1031 }
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001032 comparison[[runner_label_col]] <- character(0)
1033 comparison[[runner_value_col]] <- numeric(0)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001034 comparison[[loser_label_col]] <- character(0)
1035 comparison[[loser_value_col]] <- numeric(0)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001036 if (has_urls) {
1037 comparison[[loser_url_col]] <- character(0)
1038 }
Marc Kupietzb2862d42025-10-18 10:17:49 +02001039 comparison[[max_delta_col]] <- numeric(0)
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001040 next
1041 }
1042
1043 score_matrix <- as.matrix(score_values)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001044 storage.mode(score_matrix) <- "numeric"
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001045
Marc Kupietzb2862d42025-10-18 10:17:49 +02001046 n_rows <- nrow(score_matrix)
1047 winner_labels <- rep(NA_character_, n_rows)
1048 winner_values <- rep(NA_real_, n_rows)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001049 winner_urls <- rep(NA_character_, n_rows)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001050 runner_labels <- rep(NA_character_, n_rows)
1051 runner_values <- rep(NA_real_, n_rows)
1052 loser_labels <- rep(NA_character_, n_rows)
1053 loser_values <- rep(NA_real_, n_rows)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001054 loser_urls <- rep(NA_character_, n_rows)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001055 max_deltas <- rep(NA_real_, n_rows)
1056
Marc Kupietzb2862d42025-10-18 10:17:49 +02001057 if (n_rows > 0) {
1058 for (i in seq_len(n_rows)) {
1059 numeric_row <- as.numeric(score_matrix[i, ])
1060 if (all(is.na(numeric_row))) {
1061 next
1062 }
1063
Marc Kupietz9894a372025-10-18 14:51:29 +02001064 replacement <- score_replacements[[col]]
1065 fallback_min <- suppressWarnings(min(numeric_row, na.rm = TRUE))
1066 if (!is.finite(fallback_min)) {
1067 fallback_min <- 0
Marc Kupietzb2862d42025-10-18 10:17:49 +02001068 }
Marc Kupietz9894a372025-10-18 14:51:29 +02001069 if (!is.null(replacement) && is.finite(replacement)) {
1070 replacement <- min(replacement, fallback_min)
1071 } else {
1072 replacement <- fallback_min
1073 }
1074 if (!is.finite(replacement)) {
1075 replacement <- 0
1076 }
1077 if (any(is.na(numeric_row))) {
1078 numeric_row[is.na(numeric_row)] <- replacement
1079 }
Marc Kupietzb2862d42025-10-18 10:17:49 +02001080 score_matrix[i, ] <- numeric_row
1081
1082 max_val <- suppressWarnings(max(numeric_row, na.rm = TRUE))
1083 max_idx <- which(numeric_row == max_val)
Marc Kupietz28a29842025-10-18 12:25:09 +02001084 winner_labels[i] <- collapse_label_values(max_idx, safe_labels)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001085 winner_values[i] <- max_val
Marc Kupietz09b1c082026-05-01 14:45:47 +02001086 if (has_urls) {
1087 winner_urls[i] <- collapse_url_values(max_idx, url_values[i, ])
1088 }
Marc Kupietzb2862d42025-10-18 10:17:49 +02001089
1090 unique_vals <- sort(unique(numeric_row), decreasing = TRUE)
1091 if (length(unique_vals) >= 2) {
1092 runner_val <- unique_vals[2]
1093 runner_idx <- which(numeric_row == runner_val)
Marc Kupietz28a29842025-10-18 12:25:09 +02001094 runner_labels[i] <- collapse_label_values(runner_idx, safe_labels)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001095 runner_values[i] <- runner_val
1096 }
1097
1098 min_val <- suppressWarnings(min(numeric_row, na.rm = TRUE))
1099 min_idx <- which(numeric_row == min_val)
Marc Kupietz28a29842025-10-18 12:25:09 +02001100 loser_labels[i] <- collapse_label_values(min_idx, safe_labels)
Marc Kupietzb2862d42025-10-18 10:17:49 +02001101 loser_values[i] <- min_val
Marc Kupietz09b1c082026-05-01 14:45:47 +02001102 if (has_urls) {
1103 loser_urls[i] <- collapse_url_values(min_idx, url_values[i, ])
1104 }
Marc Kupietzb2862d42025-10-18 10:17:49 +02001105
1106 if (is.finite(max_val) && is.finite(min_val)) {
1107 max_deltas[i] <- max_val - min_val
1108 }
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001109 }
Marc Kupietzb2862d42025-10-18 10:17:49 +02001110 }
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001111
Marc Kupietzb2862d42025-10-18 10:17:49 +02001112 comparison[, value_cols] <- score_matrix
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001113 comparison[[winner_label_col]] <- winner_labels
1114 comparison[[winner_value_col]] <- winner_values
Marc Kupietz09b1c082026-05-01 14:45:47 +02001115 if (has_urls) {
1116 comparison[[winner_url_col]] <- winner_urls
1117 }
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001118 comparison[[runner_label_col]] <- runner_labels
1119 comparison[[runner_value_col]] <- runner_values
Marc Kupietzb2862d42025-10-18 10:17:49 +02001120 comparison[[loser_label_col]] <- loser_labels
1121 comparison[[loser_value_col]] <- loser_values
Marc Kupietz09b1c082026-05-01 14:45:47 +02001122 if (has_urls) {
1123 comparison[[loser_url_col]] <- loser_urls
1124 }
Marc Kupietzb2862d42025-10-18 10:17:49 +02001125 comparison[[max_delta_col]] <- max_deltas
Marc Kupietz5e35d7a2025-10-17 21:21:22 +02001126 }
1127
Marc Kupietz28a29842025-10-18 12:25:09 +02001128 for (col in score_cols) {
1129 rank_cols <- paste0("rank_", labels, "_", col)
1130 existing <- rank_cols %in% names(comparison)
1131 if (!any(existing)) {
1132 next
1133 }
1134 rank_cols <- rank_cols[existing]
1135 safe_labels <- labels[existing]
1136 rank_values <- comparison[, rank_cols, drop = FALSE]
1137
1138 winner_rank_label_col <- paste0("winner_rank_", col)
1139 winner_rank_value_col <- paste0("winner_rank_", col, "_value")
Marc Kupietz09b1c082026-05-01 14:45:47 +02001140 winner_rank_url_col <- paste0("winner_rank_", col, "_webUIRequestUrl")
Marc Kupietz28a29842025-10-18 12:25:09 +02001141 runner_rank_label_col <- paste0("runner_up_rank_", col)
1142 runner_rank_value_col <- paste0("runner_up_rank_", col, "_value")
1143 loser_rank_label_col <- paste0("loser_rank_", col)
1144 loser_rank_value_col <- paste0("loser_rank_", col, "_value")
Marc Kupietz09b1c082026-05-01 14:45:47 +02001145 loser_rank_url_col <- paste0("loser_rank_", col, "_webUIRequestUrl")
Marc Kupietz28a29842025-10-18 12:25:09 +02001146 max_delta_rank_col <- paste0("max_delta_rank_", col)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001147 url_cols <- paste0("webUIRequestUrl_", safe_labels)
1148 has_urls <- all(url_cols %in% names(comparison))
1149 url_values <- if (has_urls) comparison[, url_cols, drop = FALSE] else NULL
Marc Kupietz28a29842025-10-18 12:25:09 +02001150
1151 if (nrow(rank_values) == 0) {
1152 comparison[[winner_rank_label_col]] <- character(0)
1153 comparison[[winner_rank_value_col]] <- numeric(0)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001154 if (has_urls) {
1155 comparison[[winner_rank_url_col]] <- character(0)
1156 }
Marc Kupietz28a29842025-10-18 12:25:09 +02001157 comparison[[runner_rank_label_col]] <- character(0)
1158 comparison[[runner_rank_value_col]] <- numeric(0)
1159 comparison[[loser_rank_label_col]] <- character(0)
1160 comparison[[loser_rank_value_col]] <- numeric(0)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001161 if (has_urls) {
1162 comparison[[loser_rank_url_col]] <- character(0)
1163 }
Marc Kupietz28a29842025-10-18 12:25:09 +02001164 comparison[[max_delta_rank_col]] <- numeric(0)
1165 next
1166 }
1167
Marc Kupietzdb2fabd2026-04-27 15:01:37 +02001168 rank_matrix <- as.matrix(rank_values)
1169 storage.mode(rank_matrix) <- "numeric"
Marc Kupietz28a29842025-10-18 12:25:09 +02001170
1171 n_rows <- nrow(rank_matrix)
1172 winner_labels <- rep(NA_character_, n_rows)
1173 winner_values <- rep(NA_real_, n_rows)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001174 winner_urls <- rep(NA_character_, n_rows)
Marc Kupietz28a29842025-10-18 12:25:09 +02001175 runner_labels <- rep(NA_character_, n_rows)
1176 runner_values <- rep(NA_real_, n_rows)
1177 loser_labels <- rep(NA_character_, n_rows)
1178 loser_values <- rep(NA_real_, n_rows)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001179 loser_urls <- rep(NA_character_, n_rows)
Marc Kupietz28a29842025-10-18 12:25:09 +02001180 max_deltas <- rep(NA_real_, n_rows)
1181
1182 for (i in seq_len(n_rows)) {
1183 numeric_row <- as.numeric(rank_matrix[i, ])
1184 if (all(is.na(numeric_row))) {
1185 next
1186 }
1187
1188 if (length(rank_cols) > 0) {
1189 replacement_vec <- rank_replacements[rank_cols]
1190 replacement_vec[is.na(replacement_vec)] <- nrow(comparison) + 1
1191 missing_idx <- which(is.na(numeric_row))
1192 if (length(missing_idx) > 0) {
1193 numeric_row[missing_idx] <- replacement_vec[missing_idx]
1194 }
1195 }
1196
1197 valid_idx <- seq_along(numeric_row)
1198 valid_values <- numeric_row[valid_idx]
1199 min_val <- suppressWarnings(min(valid_values, na.rm = TRUE))
1200 min_positions <- valid_idx[which(valid_values == min_val)]
1201 winner_labels[i] <- collapse_label_values(min_positions, safe_labels)
1202 winner_values[i] <- min_val
Marc Kupietz09b1c082026-05-01 14:45:47 +02001203 if (has_urls) {
1204 winner_urls[i] <- collapse_url_values(min_positions, url_values[i, ])
1205 }
Marc Kupietz28a29842025-10-18 12:25:09 +02001206
1207 ordered_vals <- sort(unique(valid_values), decreasing = FALSE)
1208 if (length(ordered_vals) >= 2) {
1209 runner_val <- ordered_vals[2]
1210 runner_positions <- valid_idx[which(valid_values == runner_val)]
1211 runner_labels[i] <- collapse_label_values(runner_positions, safe_labels)
1212 runner_values[i] <- runner_val
1213 }
1214
1215 max_val <- suppressWarnings(max(valid_values, na.rm = TRUE))
1216 max_positions <- valid_idx[which(valid_values == max_val)]
1217 loser_labels[i] <- collapse_label_values(max_positions, safe_labels)
1218 loser_values[i] <- max_val
Marc Kupietz09b1c082026-05-01 14:45:47 +02001219 if (has_urls) {
1220 loser_urls[i] <- collapse_url_values(max_positions, url_values[i, ])
1221 }
Marc Kupietz28a29842025-10-18 12:25:09 +02001222
1223 if (is.finite(max_val) && is.finite(min_val)) {
1224 max_deltas[i] <- max_val - min_val
1225 }
1226 }
1227
1228 comparison[[winner_rank_label_col]] <- winner_labels
1229 comparison[[winner_rank_value_col]] <- winner_values
Marc Kupietz09b1c082026-05-01 14:45:47 +02001230 if (has_urls) {
1231 comparison[[winner_rank_url_col]] <- winner_urls
1232 }
Marc Kupietz28a29842025-10-18 12:25:09 +02001233 comparison[[runner_rank_label_col]] <- runner_labels
1234 comparison[[runner_rank_value_col]] <- runner_values
1235 comparison[[loser_rank_label_col]] <- loser_labels
1236 comparison[[loser_rank_value_col]] <- loser_values
Marc Kupietz09b1c082026-05-01 14:45:47 +02001237 if (has_urls) {
1238 comparison[[loser_rank_url_col]] <- loser_urls
1239 }
Marc Kupietz28a29842025-10-18 12:25:09 +02001240 comparison[[max_delta_rank_col]] <- max_deltas
1241 }
1242
Marc Kupietz130a2a22025-10-18 16:09:23 +02001243 for (col in score_cols) {
1244 pct_cols <- paste0("percentile_rank_", labels, "_", col)
1245 existing <- pct_cols %in% names(comparison)
1246 if (!any(existing)) {
1247 next
1248 }
1249 pct_cols <- pct_cols[existing]
1250 safe_labels <- labels[existing]
1251 pct_values <- comparison[, pct_cols, drop = FALSE]
1252
1253 winner_pct_label_col <- paste0("winner_percentile_rank_", col)
1254 winner_pct_value_col <- paste0("winner_percentile_rank_", col, "_value")
Marc Kupietz09b1c082026-05-01 14:45:47 +02001255 winner_pct_url_col <- paste0("winner_percentile_rank_", col, "_webUIRequestUrl")
Marc Kupietz130a2a22025-10-18 16:09:23 +02001256 runner_pct_label_col <- paste0("runner_up_percentile_rank_", col)
1257 runner_pct_value_col <- paste0("runner_up_percentile_rank_", col, "_value")
1258 loser_pct_label_col <- paste0("loser_percentile_rank_", col)
1259 loser_pct_value_col <- paste0("loser_percentile_rank_", col, "_value")
Marc Kupietz09b1c082026-05-01 14:45:47 +02001260 loser_pct_url_col <- paste0("loser_percentile_rank_", col, "_webUIRequestUrl")
Marc Kupietz130a2a22025-10-18 16:09:23 +02001261 max_delta_pct_col <- paste0("max_delta_percentile_rank_", col)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001262 url_cols <- paste0("webUIRequestUrl_", safe_labels)
1263 has_urls <- all(url_cols %in% names(comparison))
1264 url_values <- if (has_urls) comparison[, url_cols, drop = FALSE] else NULL
Marc Kupietz130a2a22025-10-18 16:09:23 +02001265
1266 if (nrow(pct_values) == 0) {
1267 comparison[[winner_pct_label_col]] <- character(0)
1268 comparison[[winner_pct_value_col]] <- numeric(0)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001269 if (has_urls) {
1270 comparison[[winner_pct_url_col]] <- character(0)
1271 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001272 comparison[[runner_pct_label_col]] <- character(0)
1273 comparison[[runner_pct_value_col]] <- numeric(0)
1274 comparison[[loser_pct_label_col]] <- character(0)
1275 comparison[[loser_pct_value_col]] <- numeric(0)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001276 if (has_urls) {
1277 comparison[[loser_pct_url_col]] <- character(0)
1278 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001279 comparison[[max_delta_pct_col]] <- numeric(0)
1280 next
1281 }
1282
1283 pct_matrix <- as.matrix(pct_values)
1284 storage.mode(pct_matrix) <- "numeric"
1285
1286 n_rows <- nrow(pct_matrix)
1287 winner_labels <- rep(NA_character_, n_rows)
1288 winner_values <- rep(NA_real_, n_rows)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001289 winner_urls <- rep(NA_character_, n_rows)
Marc Kupietz130a2a22025-10-18 16:09:23 +02001290 runner_labels <- rep(NA_character_, n_rows)
1291 runner_values <- rep(NA_real_, n_rows)
1292 loser_labels <- rep(NA_character_, n_rows)
1293 loser_values <- rep(NA_real_, n_rows)
Marc Kupietz09b1c082026-05-01 14:45:47 +02001294 loser_urls <- rep(NA_character_, n_rows)
Marc Kupietz130a2a22025-10-18 16:09:23 +02001295 max_deltas <- rep(NA_real_, n_rows)
1296
1297 if (n_rows > 0) {
1298 for (i in seq_len(n_rows)) {
1299 numeric_row <- as.numeric(pct_matrix[i, ])
1300 if (all(is.na(numeric_row))) {
1301 next
1302 }
1303
1304 if (any(is.na(numeric_row))) {
1305 numeric_row[is.na(numeric_row)] <- 0
1306 }
1307 pct_matrix[i, ] <- numeric_row
1308
1309 max_val <- suppressWarnings(max(numeric_row, na.rm = TRUE))
1310 max_idx <- which(numeric_row == max_val)
1311 winner_labels[i] <- collapse_label_values(max_idx, safe_labels)
1312 winner_values[i] <- max_val
Marc Kupietz09b1c082026-05-01 14:45:47 +02001313 if (has_urls) {
1314 winner_urls[i] <- collapse_url_values(max_idx, url_values[i, ])
1315 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001316
1317 unique_vals <- sort(unique(numeric_row), decreasing = TRUE)
1318 if (length(unique_vals) >= 2) {
1319 runner_val <- unique_vals[2]
1320 runner_idx <- which(numeric_row == runner_val)
1321 runner_labels[i] <- collapse_label_values(runner_idx, safe_labels)
1322 runner_values[i] <- runner_val
1323 }
1324
1325 min_val <- suppressWarnings(min(numeric_row, na.rm = TRUE))
1326 min_idx <- which(numeric_row == min_val)
1327 loser_labels[i] <- collapse_label_values(min_idx, safe_labels)
1328 loser_values[i] <- min_val
Marc Kupietz09b1c082026-05-01 14:45:47 +02001329 if (has_urls) {
1330 loser_urls[i] <- collapse_url_values(min_idx, url_values[i, ])
1331 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001332
1333 if (is.finite(max_val) && is.finite(min_val)) {
1334 max_deltas[i] <- max_val - min_val
1335 }
1336 }
1337 }
1338
1339 comparison[, pct_cols] <- pct_matrix
1340 comparison[[winner_pct_label_col]] <- winner_labels
1341 comparison[[winner_pct_value_col]] <- winner_values
Marc Kupietz09b1c082026-05-01 14:45:47 +02001342 if (has_urls) {
1343 comparison[[winner_pct_url_col]] <- winner_urls
1344 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001345 comparison[[runner_pct_label_col]] <- runner_labels
1346 comparison[[runner_pct_value_col]] <- runner_values
1347 comparison[[loser_pct_label_col]] <- loser_labels
1348 comparison[[loser_pct_value_col]] <- loser_values
Marc Kupietz09b1c082026-05-01 14:45:47 +02001349 if (has_urls) {
1350 comparison[[loser_pct_url_col]] <- loser_urls
1351 }
Marc Kupietz130a2a22025-10-18 16:09:23 +02001352 comparison[[max_delta_pct_col]] <- max_deltas
1353 }
1354
Marc Kupietzd7bb5cb2026-08-31 10:18:02 +02001355 for (flag_col in names(imputed_flags)) {
1356 comparison[[flag_col]] <- imputed_flags[[flag_col]]
1357 }
1358 if (length(imputed_flags) > 0) {
1359 comparison$n_imputed <- as.integer(Reduce(`+`, lapply(imputed_flags, as.integer)))
1360 } else {
1361 comparison$n_imputed <- rep(0L, nrow(comparison))
1362 }
1363 comparison$imputed <- comparison$n_imputed > 0L
1364
Marc Kupietz424cb782026-08-31 10:19:29 +02001365 n_imputed_rows <- sum(comparison$imputed)
1366 if (n_imputed_rows > 0) {
1367 log_info(verbose, sprintf(
1368 paste0(
1369 "Imputed scores for %d of %d node/collocate combinations (%d of %d label cells) ",
1370 "that are not attested in every virtual corpus. Their delta and winner/loser ",
1371 "columns reflect presence vs. absence rather than a measured contrast; see the ",
1372 "`imputed` column and `queryMissingScores`.\n"
1373 ),
1374 n_imputed_rows,
1375 nrow(comparison),
1376 sum(comparison$n_imputed),
1377 nrow(comparison) * length(labels)
1378 ))
1379 }
1380
Marc Kupietz09b1c082026-05-01 14:45:47 +02001381 collapse_consensus_url_columns <- function(url_cols) {
1382 if (length(url_cols) == 0) {
1383 return(rep(NA_character_, nrow(comparison)))
1384 }
1385 vapply(seq_len(nrow(comparison)), function(i) {
1386 urls <- unlist(comparison[i, url_cols, drop = FALSE], use.names = FALSE)
1387 urls <- as.character(urls)
1388 urls <- urls[!is.na(urls) & urls != ""]
1389 urls <- unique(urls)
1390 if (length(urls) == 1) {
1391 urls
1392 } else {
1393 NA_character_
1394 }
1395 }, character(1))
1396 }
1397
1398 winner_score_url_cols <- intersect(paste0("winner_", score_cols, "_webUIRequestUrl"), names(comparison))
1399 loser_score_url_cols <- intersect(paste0("loser_", score_cols, "_webUIRequestUrl"), names(comparison))
1400 if (length(winner_score_url_cols) > 0) {
1401 comparison$winner_webUIRequestUrl <- collapse_consensus_url_columns(winner_score_url_cols)
1402 }
1403 if (length(loser_score_url_cols) > 0) {
1404 comparison$loser_webUIRequestUrl <- collapse_consensus_url_columns(loser_score_url_cols)
1405 }
1406
1407 url_helper_cols <- intersect(paste0("webUIRequestUrl_", labels), names(comparison))
1408 if (length(url_helper_cols) > 0) {
1409 comparison <- dplyr::select(comparison, -dplyr::all_of(url_helper_cols))
1410 }
1411
Marc Kupietzc4540a22025-10-14 17:39:53 +02001412 dplyr::left_join(result, comparison, by = c("node", "collocate"))
1413}
1414
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001415#' @importFrom magrittr debug_pipe
Marc Kupietz2b17b212023-08-27 17:47:26 +02001416#' @importFrom stringr str_detect
1417#' @importFrom dplyr as_tibble tibble rename filter anti_join tibble bind_rows case_when
1418#'
1419matches2FreqTable <- function(matches,
1420 index = 0,
1421 minOccur = 5,
1422 leftContextSize = 5,
1423 rightContextSize = 5,
1424 ignoreCollocateCase = FALSE,
1425 stopwords = c(),
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001426 collocateFilterRegex = "^[:alnum:]+-?[:alnum:]*$",
Marc Kupietz2b17b212023-08-27 17:47:26 +02001427 oldTable = data.frame(word = rep(NA, 1), frequency = rep(NA, 1)),
1428 verbose = TRUE) {
1429 word <- NULL # https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check
1430 frequency <- NULL
1431
1432 if (nrow(matches) < 1) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001433 dplyr::tibble(word = c(), frequency = c())
Marc Kupietz2b17b212023-08-27 17:47:26 +02001434 } else if (index == 0) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001435 if (!"tokens" %in% colnames(matches) || !is.list(matches$tokens)) {
Marc Kupietz2b17b212023-08-27 17:47:26 +02001436 log_info(verbose, "Outdated KorAP server: Falling back to client side tokenization.\n")
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001437 return(snippet2FreqTable(matches$snippet, minOccur, leftContextSize, rightContextSize,
1438 ignoreCollocateCase = ignoreCollocateCase,
1439 stopwords = stopwords, oldTable = oldTable, verbose = verbose
1440 ))
Marc Kupietz2b17b212023-08-27 17:47:26 +02001441 }
1442 log_info(verbose, paste("Joining", nrow(matches), "kwics\n"))
Marc Kupietza25fbd92025-10-14 17:38:09 +02001443 for (i in seq_len(nrow(matches))) {
Marc Kupietz2b17b212023-08-27 17:47:26 +02001444 oldTable <- matches2FreqTable(
1445 matches,
1446 i,
1447 leftContextSize = leftContextSize,
1448 rightContextSize = rightContextSize,
1449 collocateFilterRegex = collocateFilterRegex,
1450 oldTable = oldTable,
1451 stopwords = stopwords
1452 )
1453 }
1454 log_info(verbose, paste("Aggregating", length(oldTable$word), "tokens\n"))
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001455 oldTable |>
Marc Kupietz4cd066d2025-02-28 15:48:23 +01001456 group_by(word) |>
1457 mutate(word = dplyr::case_when(ignoreCollocateCase ~ tolower(word), TRUE ~ word)) |>
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001458 summarise(frequency = sum(frequency), .groups = "drop") |>
Marc Kupietz2b17b212023-08-27 17:47:26 +02001459 arrange(desc(frequency))
1460 } else {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001461 stopwordsTable <- dplyr::tibble(word = stopwords)
Marc Kupietz2b17b212023-08-27 17:47:26 +02001462
1463 left <- tail(unlist(matches$tokens$left[index]), leftContextSize)
1464
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001465 # cat(paste("left:", left, "\n", collapse=" "))
Marc Kupietz2b17b212023-08-27 17:47:26 +02001466
1467 right <- head(unlist(matches$tokens$right[index]), rightContextSize)
1468
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001469 # cat(paste("right:", right, "\n", collapse=" "))
Marc Kupietz2b17b212023-08-27 17:47:26 +02001470
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001471 if (length(left) + length(right) == 0) {
Marc Kupietz2b17b212023-08-27 17:47:26 +02001472 oldTable
1473 } else {
Marc Kupietz4cd066d2025-02-28 15:48:23 +01001474 table(c(left, right)) |>
1475 dplyr::as_tibble(.name_repair = "minimal") |>
1476 dplyr::rename(word = 1, frequency = 2) |>
1477 dplyr::filter(str_detect(word, collocateFilterRegex)) |>
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001478 dplyr::anti_join(stopwordsTable, by = "word") |>
Marc Kupietz2b17b212023-08-27 17:47:26 +02001479 dplyr::bind_rows(oldTable)
1480 }
1481 }
1482}
1483
1484#' @importFrom magrittr debug_pipe
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001485#' @importFrom stringr str_match str_split str_detect
1486#' @importFrom dplyr as_tibble tibble rename filter anti_join tibble bind_rows case_when
1487#'
1488snippet2FreqTable <- function(snippet,
1489 minOccur = 5,
1490 leftContextSize = 5,
1491 rightContextSize = 5,
1492 ignoreCollocateCase = FALSE,
1493 stopwords = c(),
1494 tokenizeRegex = "([! )(\uc2\uab,.:?\u201e\u201c\'\"]+|&quot;)",
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001495 collocateFilterRegex = "^[:alnum:]+-?[:alnum:]*$",
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001496 oldTable = data.frame(word = rep(NA, 1), frequency = rep(NA, 1)),
1497 verbose = TRUE) {
1498 word <- NULL # https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check
1499 frequency <- NULL
1500
1501 if (length(snippet) < 1) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001502 dplyr::tibble(word = c(), frequency = c())
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001503 } else if (length(snippet) > 1) {
Marc Kupietza47d1502023-04-18 15:26:47 +02001504 log_info(verbose, paste("Joining", length(snippet), "kwics\n"))
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001505 for (s in snippet) {
1506 oldTable <- snippet2FreqTable(
1507 s,
1508 leftContextSize = leftContextSize,
1509 rightContextSize = rightContextSize,
Marc Kupietz47d0d2b2021-12-19 16:38:52 +01001510 collocateFilterRegex = collocateFilterRegex,
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001511 oldTable = oldTable,
1512 stopwords = stopwords
1513 )
1514 }
Marc Kupietza47d1502023-04-18 15:26:47 +02001515 log_info(verbose, paste("Aggregating", length(oldTable$word), "tokens\n"))
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001516 oldTable |>
Marc Kupietz4cd066d2025-02-28 15:48:23 +01001517 group_by(word) |>
1518 mutate(word = dplyr::case_when(ignoreCollocateCase ~ tolower(word), TRUE ~ word)) |>
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001519 summarise(frequency = sum(frequency), .groups = "drop") |>
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001520 arrange(desc(frequency))
1521 } else {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001522 stopwordsTable <- dplyr::tibble(word = stopwords)
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001523 match <-
1524 str_match(
1525 snippet,
1526 '<span class="context-left">(<span class="more"></span>)?(.*[^ ]) *</span><span class="match"><mark>.*</mark></span><span class="context-right"> *([^<]*)'
1527 )
1528
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001529 left <- if (leftContextSize > 0) {
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001530 tail(unlist(str_split(match[1, 3], tokenizeRegex)), leftContextSize)
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001531 } else {
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001532 ""
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001533 }
1534 # cat(paste("left:", left, "\n", collapse=" "))
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001535
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001536 right <- if (rightContextSize > 0) {
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001537 head(unlist(str_split(match[1, 4], tokenizeRegex)), rightContextSize)
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001538 } else {
1539 ""
1540 }
1541 # cat(paste("right:", right, "\n", collapse=" "))
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001542
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001543 if (is.na(left[1]) || is.na(right[1]) || length(left) + length(right) == 0) {
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001544 oldTable
1545 } else {
Marc Kupietz4cd066d2025-02-28 15:48:23 +01001546 table(c(left, right)) |>
1547 dplyr::as_tibble(.name_repair = "minimal") |>
1548 dplyr::rename(word = 1, frequency = 2) |>
1549 dplyr::filter(str_detect(word, collocateFilterRegex)) |>
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001550 dplyr::anti_join(stopwordsTable, by = "word") |>
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001551 dplyr::bind_rows(oldTable)
1552 }
1553 }
1554}
1555
1556#' Preliminary synsemantic stopwords function
1557#'
1558#' @description
Marc Kupietz67edcb52021-09-20 21:54:24 +02001559#' `r lifecycle::badge("experimental")`
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001560#'
1561#' Preliminary synsemantic stopwords function to be used in collocation analysis.
1562#'
1563#' @details
1564#' Currently only suitable for German. See stopwords package for other languages.
1565#'
1566#' @param ... future arguments for language detection
1567#'
1568#' @family collocation analysis functions
1569#' @return Vector of synsemantic stopwords.
1570#' @export
1571synsemanticStopwords <- function(...) {
Marc Kupietzc79155b2025-10-19 13:42:55 +02001572 base <- c(
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001573 "der",
1574 "die",
1575 "und",
1576 "in",
1577 "den",
1578 "von",
1579 "mit",
1580 "das",
1581 "zu",
1582 "im",
1583 "ist",
1584 "auf",
1585 "sich",
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001586 "des",
1587 "dem",
1588 "nicht",
1589 "ein",
1590 "eine",
1591 "es",
1592 "auch",
1593 "an",
1594 "als",
1595 "am",
1596 "aus",
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001597 "bei",
1598 "er",
1599 "dass",
1600 "sie",
1601 "nach",
1602 "um",
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001603 "zum",
1604 "noch",
1605 "war",
1606 "einen",
1607 "einer",
1608 "wie",
1609 "einem",
1610 "vor",
1611 "bis",
1612 "\u00fcber",
1613 "so",
1614 "aber",
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001615 "diese",
Marc Kupietzc79155b2025-10-19 13:42:55 +02001616 "oder"
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001617 )
Marc Kupietzc79155b2025-10-19 13:42:55 +02001618
1619 lower <- unique(tolower(base))
1620 capitalized <- paste0(toupper(substr(lower, 1, 1)), substring(lower, 2))
1621
1622 unique(c(lower, capitalized))
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001623}
1624
Marc Kupietz5a336b62021-11-27 17:51:35 +01001625
Marc Kupietz76b05592021-12-19 16:26:15 +01001626# #' @export
Marc Kupietz5a336b62021-11-27 17:51:35 +01001627findExample <-
1628 function(kco,
1629 query,
1630 vc = "",
1631 matchOnly = TRUE) {
1632 out <- character(length = length(query))
1633
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001634 if (length(vc) < length(query)) {
Marc Kupietz5a336b62021-11-27 17:51:35 +01001635 vc <- rep(vc, length(query))
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001636 }
Marc Kupietz5a336b62021-11-27 17:51:35 +01001637
1638 for (i in seq_along(query)) {
1639 q <- corpusQuery(kco, paste0("(", query[i], ")"), vc = vc[i], metadataOnly = FALSE)
Marc Kupietzb811ffb2021-12-07 10:34:10 +01001640 if (q@totalResults > 0) {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001641 q <- fetchNext(q, maxFetch = 50, randomizePageOrder = F)
Marc Kupietzb811ffb2021-12-07 10:34:10 +01001642 example <- as.character((q@collectedMatches)$snippet[1])
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001643 out[i] <- if (matchOnly) {
1644 gsub(".*<mark>(.+)</mark>.*", "\\1", example)
Marc Kupietz5a336b62021-11-27 17:51:35 +01001645 } else {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001646 stringr::str_replace(example, "<[^>]*>", "")
Marc Kupietz5a336b62021-11-27 17:51:35 +01001647 }
Marc Kupietzb811ffb2021-12-07 10:34:10 +01001648 } else {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001649 out[i] <- ""
Marc Kupietzb811ffb2021-12-07 10:34:10 +01001650 }
Marc Kupietz5a336b62021-11-27 17:51:35 +01001651 }
1652 out
1653 }
1654
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001655collocatesQuery <-
1656 function(kco,
1657 query,
1658 vc = "",
1659 minOccur = 5,
1660 leftContextSize = 5,
1661 rightContextSize = 5,
1662 searchHitsSampleLimit = 20000,
1663 ignoreCollocateCase = FALSE,
1664 stopwords = c(),
Marc Kupietzb2862d42025-10-18 10:17:49 +02001665 collocateFilterRegex = "^[:alnum:]+-?[:alnum:]*$",
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001666 ...) {
1667 frequency <- NULL
1668 q <- corpusQuery(kco, query, vc, metadataOnly = F, ...)
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001669 if (q@totalResults == 0) {
1670 tibble(word = c(), frequency = c())
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001671 } else {
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001672 q <- fetchNext(q, maxFetch = searchHitsSampleLimit, randomizePageOrder = TRUE)
1673 matches2FreqTable(q@collectedMatches,
1674 0,
1675 minOccur = minOccur,
1676 leftContextSize = leftContextSize,
1677 rightContextSize = rightContextSize,
1678 ignoreCollocateCase = ignoreCollocateCase,
1679 stopwords = stopwords,
Marc Kupietzb2862d42025-10-18 10:17:49 +02001680 collocateFilterRegex = collocateFilterRegex,
Marc Kupietz6dfeed92025-06-03 11:58:06 +02001681 ...,
1682 verbose = kco@verbose
1683 ) |>
Marc Kupietz4cd066d2025-02-28 15:48:23 +01001684 mutate(frequency = frequency * q@totalResults / min(q@totalResults, searchHitsSampleLimit)) |>
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001685 filter(frequency >= minOccur)
1686 }
1687 }