File: eval_with.R

package info (click to toggle)
r-bioc-glmgampoi 1.2.0%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 704 kB
  • sloc: cpp: 523; ansic: 114; sh: 13; makefile: 2
file content (29 lines) | stat: -rw-r--r-- 958 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

eval_with <- function(statement, data){
  stmnt_capture <- substitute(statement)
  eval_with_q(stmnt_capture, data = data, env = parent.frame())
}

eval_with_q <- function(statement, data, env = parent.frame()){
  statement_envir <- new.env(parent = env)
  tryCatch({
    res <- eval(statement, envir = as.list(data), enclos = statement_envir)
    if(! is.numeric(res)){
      if(is.character(res) && length(res) == 1){
        # If contrast was a string, eval will just spit it out the same way
        res <- eval(parse(text = res), envir= as.list(data), enclos = statement_envir)
      }
    }
  }, error = function(e){
    # Try to extract text from error message
    match <- regmatches(e$message, regexec("object '(.+)' not found", e$message))[[1]]
    if(length(match) == 2){
      stop("Object '", match[2], "' not found. Allowed variables are:\n",
           paste0(names(df), collapse = ", "))
    }else{
      stop(e$message)
    }
  })
  res
}