Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the list of in-built functions used within a function

Tags:

function

r

Lets say I have a function named Fun1 within which I am using many different in-built functions of R for different different processes. Then how can I get a list of in-built functions used inside this function Fun1

  Fun1 <- function(x,y){
  sum(x,y)
  mean(x,y)
  c(x,y)
  print(x)
  print(y)
  }

So My output should be like list of characters i.e. sum, mean, c, print. Because these are the in-built functions I have used inside function Fun1.

I have tried using grep function

 grep("\\(",body(Fun1),value=TRUE)
 # [1] "sum(x, y)"  "mean(x, y)" "c(x, y)"    "print(x)"   "print(y)" 

It looks ok, but arguments should not come i.e. x and y. Just the list of function names used inside body of function Fun1 here.

So my overall goal is to print the unique list of in-built functions or any create functions inside a particular function, here Fun1.

Any help on this is highly appreciated. Thanks.

like image 399
Sowmya S. Manian Avatar asked Dec 10 '22 15:12

Sowmya S. Manian


1 Answers

You could use all.vars() to get all the variable names (including functions) that appear inside the body of Fun1, then compare that with some prepared list of functions. You mention in-built functions, so I will compare it with the base package object names.

## full list of variable names inside the function body
(vars <- all.vars(body(Fun1)[-1], functions = TRUE))
# [1] "sum"   "x"     "y"     "mean"  "c"     "print"

## compare it with the base package object names
intersect(vars, ls(baseenv()))
# [1] "sum"   "mean"  "c"     "print"

I removed the first element of the function body because presumably you don't care about {, which would have been matched against the base package list.

Another possibility, albeit a bit less reliable, would be to compare the formal arguments of Fun1 to all the variable names in the function. Like I said, likely less reliable though because if you make assignments inside the function you will end up with incorrect results.

setdiff(vars, names(formals(Fun1)))
# [1] "sum"   "mean"  "c"     "print"

These are fun though, and you can fiddle around with them.

like image 73
Rich Scriven Avatar answered Jan 17 '23 15:01

Rich Scriven