r - Determining which Functions are in Code -


i trying find set of functions used in code.

  • assume followed opening bracket
  • loop regular expression grepl("somefunction\\(", code) on function names
  • specify there must else letter, underscore or dot in front of function name, frame not found in data.frame(...). possible following regex: grepl("[^a-za-z_\\.]somefunction\\(", code)
  • make sure function names @ beginning of code still found prepending spaces code
  • replace dots in function names \\.: gsub(".","\\.",thefunctions, fixed=true)

here's minimal reproducible test:

code <- "mean(pi); head(data.frame(a=1:5)); data_frame(7:9)" funs <- c("mean", "head", "head.data.frame",  "data.frame", "frame", "data_frame")  data.frame(isfound=sapply(paste0("[^a-za-z_\\.]",gsub(".","\\.",funs,fixed=true),"\\("),                            grepl, x=paste0(" ",code)),            shouldbefound=c(t,t,f,t,f,t)) 

this seems work, long , not human-readable.
there more elegant way determine of set of functions appear in code?

you can use following approach find names of functions used in r code. function get_functions can used code represented character string.

get_functions <- function(code) {   unname(find_functions(parse(text = code))) }  find_functions <- function(x, y = vector(mode = "character", length = 0)) {   if (is.symbol(x)) {     if (is.function(eval(x)))       c(y, as.character(x))   } else {     if (!is.language(x)) {       null     } else {       c(y, unlist(lapply(x, find_functions)))     }   } } 

here, find_functions called recursively since expressions can nested.

an example:

code <- "mean(pi); head(data.frame(a=1:5)); data_frame(7:9)\n paste(\"abc\", 0x28)"  get_functions(code) # [1] "mean"       "head"       "data.frame" ":"          "data_frame" ":"          "paste" 

this approach appears more safe since makes use of r's parser. furthermore, functions without parentheses can found (e.g., :).


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -