R/utils-eval.R

Defines functions without_labelled filter_text replace_x query_message redcap_logic parse_conditions

## Conditions written as text ----
# The `filter` and `expression` arguments of rd_query(), rd_event() and rd_insert_na() are R conditions written as
# text. They are parsed into R expressions (never pasted into other code and run with eval(parse())) and evaluated as
# in dplyr::filter(): first with the columns of the data and then with the objects of the environment where the user
# called the function (the console, a function or a loop). `data` refers to the data being filtered, so that the
# branching logic translated by rd_dictionary() (`data$var == 1`) can be used as a filter.

#' Parse conditions written as text
#'
#' Several conditions separated by commas must all be met, as in `dplyr::filter()`.
#'
#' @param text A single string, e.g. `"age > 50, dm == 1"`.
#' @return A list of expressions (empty when the text is empty).
#' @noRd
parse_conditions <- function(text) {
  # The final newline closes the call even if the text ends with a comment
  call <- rlang::parse_expr(paste0("list(", text, "\n)"))
  as.list(call)[-1]
}

#' Branching logic written in REDCap syntax
#'
#' The branching logic of the dictionary can be REDCap logic or R logic (e.g. translated by rd_dictionary()). It is
#' REDCap logic when it has fields between brackets outside its texts, or when it can't be R conditions: it can't be
#' read (e.g. `1 <> 1`), it assigns (e.g. `(1 = 1)`) or it uses a function that doesn't exist where the user called the
#' function (e.g. `datediff()`). Logic without fields such as `1 = 1` or `sum(1, 1) = 2` is REDCap logic.
#'
#' @param logic A branching logic.
#' @param env Environment where the user called the exported function.
#' @return `TRUE` or `FALSE`.
#' @noRd
redcap_logic <- function(logic, env) {
  if (length(logic) != 1 || is.na(logic) || !nzchar(trimws(logic))) {
    return(FALSE)
  }
  # (a field between brackets: not the `[` of R, which follows a name, a parenthesis or another bracket, e.g.
  # `v[is.finite(v)]` in the R logic of rd_dictionary() or `data[['value']]`)
  # (not in the comments of R, e.g. `data$value == 0 # [note]`)
  if (grepl("(^|[^\\w.)\\]\\[])\\[", gsub("\\s+", "", gsub("#[^\n]*", "", without_texts(logic))), perl = TRUE)) {
    return(TRUE)
  }
  conditions <- tryCatch(parse_conditions(logic), error = function(e) NULL)
  if (is.null(conditions)) {
    return(TRUE)
  }

  # Functions used by the conditions (not inside the functions they define, e.g. `(function(v, d) { r <- ... })(x, 1)` of
  # the R logic of rd_dictionary(), whose assignments and arguments are R code)
  functions <- character(0)
  find_functions <- function(expr) {
    if (is.call(expr)) {
      if (identical(expr[[1]], as.name("function"))) {
        return(invisible())
      }
      if (is.symbol(expr[[1]])) {
        functions <<- c(functions, as.character(expr[[1]]))
      }
      for (k in seq_along(expr)) {
        if (!identical(expr[[k]], quote(expr = )) && !is.null(expr[[k]])) find_functions(expr[[k]])
      }
    }
  }
  for (condition in conditions) {
    if (!identical(condition, quote(expr = ))) find_functions(condition)
  }
  functions <- unique(functions)

  any(functions %in% c("=", "<-")) || !all(vapply(functions, exists, logical(1), envir = env, mode = "function"))
}

#' Message of the queries of rd_query()
#'
#' The expression is described in words: the variable `x` is removed and the operators are written in words (e.g.
#' `x > 5` is "greater than 5"), only outside the texts between quotes and the raw strings of R, which are kept as
#' they are (e.g. `x == 'a>b'` is "equal to 'a>b'" and `x == 'A  B'` keeps its spaces). The values of the variable are
#' also kept as they are (e.g. "A  B" or " A").
#'
#' @param expression The expression of rd_query() (one message for each expression).
#' @param message A function that writes the message with the description of the expression and, if `values` are
#'   given, with the value (a function of the description and the value).
#' @param values The values of the variable (one message for each value), or none.
#' @return The message.
#' @noRd
query_message <- function(expression, message, values = NULL) {
  with_values <- length(formals(message)) > 1
  values <- as.character(values)
  if (length(expression) == 0) {
    return(if (with_values) message("", values) else message(""))
  }
  if (length(expression) > 1) {
    return(unlist(lapply(expression, query_message, message = message, values = values)))
  }
  if (is.na(expression)) {
    expression <- "NA"
  }
  operators <- c("<=", ">=", "<", ">", "&", "\\|", "!=", "==", "%in%NA", "%in%", "%nin%", "is.na\\(\\)")
  words <- c(" less than or equal to ", " greater than or equal to ", " less than ", " greater than ", " and ", " or ", " not equal to ", " equal to ", " missing ", " equal to ", " not equal to ", " missing ")
  quotes <- gregexpr(r_texts_pattern(), expression, perl = TRUE)
  texts <- regmatches(expression, quotes)[[1]]
  code <- regmatches(expression, quotes, invert = TRUE)[[1]]
  code <- vapply(code, function(s) {
    stringi::stri_replace_all_regex(gsub(" ", "", gsub("\\bx\\b", "", s)), pattern = operators, replacement = words, vectorize_all = FALSE)
  }, character(1), USE.NAMES = FALSE)

  # The texts and the value are set aside while the message is written (its spaces are joined)
  base <- "REDCapDMquote"
  while (any(grepl(base, c(expression, values), fixed = TRUE))) {
    base <- paste0(base, "x")
  }
  holders <- if (length(texts) > 0) paste0(base, seq_along(texts), "x") else character(0)
  description <- paste0(code, c(holders, ""), collapse = "")
  value_holder <- paste0(base, "valuex")
  out <- if (!with_values) {
    message(description)
  } else if (length(values) == 0) {
    message(description, character(0))
  } else {
    rep(message(description, value_holder), length(values))
  }
  for (k in rev(seq_along(texts))) {
    out <- gsub(holders[k], texts[k], out, fixed = TRUE)
  }
  if (with_values && length(values) > 0) {
    # (a value NA is written "NA", as paste() does)
    out <- stringi::stri_replace_first_fixed(out, value_holder, ifelse(is.na(values), "NA", values))
  }
  out
}

#' Replace the variable `x` of an expression of rd_query()
#'
#' Only the name `x` is replaced: an "x" inside a text value (`x == 'x'`) or inside another name (`max_x`) is kept.
#'
#' @param expr An expression.
#' @param variable Name of the variable.
#' @noRd
replace_x <- function(expr, variable) {
  if (is.symbol(expr) && identical(expr, quote(x))) {
    return(as.symbol(variable))
  }
  if (is.call(expr)) {
    # Inside a function with an argument `x` (e.g. `function(x) is.na(x)` or `\(x) is.na(x)`), `x` is that argument
    if (identical(expr[[1]], as.name("function"))) {
      args <- expr[[2]]
      if ("x" %in% names(args)) {
        return(expr)
      }
      # (the default values of the other arguments and the body can use the variable)
      for (k in seq_along(args)) {
        if (!identical(args[[k]], quote(expr = )) && !is.null(args[[k]])) args[[k]] <- replace_x(args[[k]], variable)
      }
      if (!is.null(args)) expr[[2]] <- args
      expr[[3]] <- replace_x(expr[[3]], variable)
      return(expr)
    }
    parts <- as.list(expr)
    for (k in seq_along(parts)) {
      # (an empty argument, e.g. in `x[, 1]`, or a NULL one is kept as it is)
      if (!identical(parts[[k]], quote(expr = )) && !is.null(parts[[k]])) parts[[k]] <- replace_x(parts[[k]], variable)
    }
    return(as.call(parts))
  }
  expr
}

#' Keep the rows of a data frame that meet conditions written as text
#'
#' @param data A data frame.
#' @param text The conditions, a single string.
#' @param env Environment where the user called the exported function.
#' @param x Name of the variable that `x` stands for (only for the `expression` of rd_query()).
#' @noRd
filter_text <- function(data, text, env, x = NULL) {
  conditions <- parse_conditions(text)
  if (!is.null(x)) {
    conditions <- lapply(conditions, replace_x, variable = x)
  }

  # The conditions are evaluated without the class `labelled` of the variable labels, which some functions don't accept
  # (e.g. dplyr::between()). The rows returned are those of `data`, with their labels.
  # They only see the columns of the project: not the internal ones of the functions (`.rd_row` of rd_query()), which
  # would be selected by e.g. `if_all(where(is.numeric), ~ .x < 5)`
  plain <- without_labelled(data)
  plain <- plain[!names(plain) %in% ".rd_row"]
  eval_env <- rlang::env(env, data = plain)
  quosures <- lapply(conditions, rlang::new_quosure, env = eval_env)

  # The rows kept are known by their row names (a column with the number of each row would also be seen)
  indexed <- as.data.frame(plain)
  row_ids <- sprintf("r%d", seq_len(nrow(indexed)))
  row.names(indexed) <- row_ids
  kept <- match(row.names(dplyr::filter(indexed, !!!quosures)), row_ids)
  if (anyNA(kept)) {
    # (in case the row names were not kept)
    row_col <- utils::tail(make.unique(c(names(plain), ".row")), 1)
    plain[[row_col]] <- seq_len(nrow(plain))
    kept <- dplyr::filter(plain, !!!quosures)[[row_col]]
  }
  dplyr::slice(data, !!kept)
}

#' Remove the class `labelled` of the variable labels
#'
#' Some functions (e.g. `dplyr::between()`) don't accept it. The values and the other classes (e.g. `Date` or `factor`) are kept.
#'
#' @param data A data frame.
#' @return The data frame without the class `labelled` in its columns.
#' @noRd
without_labelled <- function(data) {
  data[] <- lapply(data, function(x) {
    if (inherits(x, "labelled")) class(x) <- setdiff(class(x), "labelled")
    x
  })
  data
}

Try the REDCapDM package in your browser

Any scripts or data that you put into this service are public.

REDCapDM documentation built on Nov. 27, 2026, 9:06 a.m.