2

Is there a way in R to list the functions that are contained in a given function?

For instance in the code below:

myFun <- function(x) { 
  res <- list(m1=mean(x), s1=sd(x), mi=min(x))
  return(res)
}

How to extract from the function myFun the names of the functions used. In this case I would like to have a vector with mean, sd and min.

I would like to do this without having to call the function (otherwise Rprof() would do the job).

Pop
  • 12,135
  • 5
  • 55
  • 68
ed82
  • 3,007
  • 3
  • 15
  • 11
  • This is quite a nontrivial task. The only idea I have is to parse `body(myFun)` somehow, with `lsf.str("package:base")` maybe? Probably an overkill. – tonytonov Feb 12 '14 at 07:21
  • There's another problem: how would you choose between, say, `mean`, and `return`? Both are functions from `base`: `grep(ls("package:base"), pattern='return')`, `grep(ls("package:base"), pattern='mean')`. – tonytonov Feb 12 '14 at 07:26

1 Answers1

8

Install pryr via devtools and github:

require(devtools)
install_github("hadley/pryr")

Then simply walk into Mordor:

fun_calls(myFun)
[1] "{"      "<-"     "list"   "mean"   "sd"     "min"    "return"

Note how there are more functions than you expected, because so much in R is a function. Feel free to apply extra logic to remove common things you aren't interested in, like { and <- (which you get when you do an assign with =) and [ (which you get if you ever subset).

Spacedman
  • 92,590
  • 12
  • 140
  • 224