R/groups.R

#' Build nested queries
#'
#' Group search terms and specify fields in bulk.
#' @param query search term
#' @param field field
#' @importFrom stringr str_extract_all
#' @export
#' @examples
#' query =
#'   "pain" @ "MeSH" +
#'    g("eeg" | "seeg", "TIAB") +
#'    g("event-related" - g("mri" | "meg", "MeSH"), "TIAB")
#' cat(query)

g = function(query, field = NULL) {

  if (!is.null(field) && nchar(field) > 0) {

    # Add field to standalone terms (if provided)
    terms = unlist(strsplit(query, "( AND | OR | NOT )"))
    specs = grepl("[\\[\\)\\()]", terms)
    for (i in seq_along(terms)) {
      if (!specs[i]) terms[i] = paste0(terms[i], "[", field, "]")
    }

    # Extract operators (spaces would double themselves if not trimmed)
    opers = unlist(str_extract_all(query, "( AND | OR | NOT )"))
    opers = gsub(" ", "", opers)

    # Due to the recycling rules, paste adds another operator to the end which
    # needs to be removed
    query = paste(terms, opers, collapse = " ")
    query = gsub("( AND| OR| NOT| )$", "", query)
  }
  paste0("(", query, ")")
}
jchrom/qbuildr documentation built on May 18, 2019, 10:23 p.m.