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

Suppose I have a function with a name Fun1in which I use many different built-in R functions for different processes. Then, how can I get a list of built-in functions used inside this functionFun1

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

So my output should be like a list of characters, i.e. sum, mean, c, print. Since these are built-in functions, I used an internal function Fun1.

I tried to use the function grep

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

This looks fine, but the arguments should not come, i.e. xand y. Just a list of function names used inside the function body Fun1here.

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

. .

+4
5

all.vars(), ( ), Fun1, . , .

## 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"

, , , {, .

, , - Fun1 . , , , , .

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

, .

+6

utils.

tokens <- utils::getParseData(parse(text=deparse(body(Fun1))))
unique(tokens[tokens[["token"]] == "SYMBOL_FUNCTION_CALL", "text"])
[1] "sum"   "mean"  "c"     "print"
+4

- .

func_list = Fun1 %>% 
  body() %>% # extracts function
  toString() %>% # converts to single string
  gsub("[{}]", "", .)  %>% # removes curly braces
  gsub("\\s*\\([^\\)]+\\)", "", .) %>% # removes all contents between brackets
  strsplit(",") %>% # splits strings at commas
  unlist() %>% # converts to vector
  trimws(., "both") # removes all white spaces before and after`

[1] "" "sum" "mean" "c" "print" "print"

> table(func_list)
func_list
          c  mean print   sum 
    1     1     1     2     1 

... , . , , ..

+2

, :

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


getFNamesInFunction <- function(f.name){
    f <- deparse(body(get(f.name)))
    f <- f[grepl(pattern = "\\(", x = f)]
    f <- sapply(X = strsplit(split = "\\(", x = f), FUN = function(x) x[1])
    unique(trimws(f[f != ""]))
}
getFNamesInFunction("Fun1")
[1] "sum"   "mean"  "c"     "print"
+1
as.list(Fun1)[3]

.

{
    sum(x, y)
    mean(x, y)
    c(x, y)
    print(x)
    print(y)
}

,

 gsub( ").*$", "", as.list(Fun1)[3])

gives you everything before the first " )" appears , which is supposed to contain the name of the first function.

Taking this as a starting point, you should include a loop that gives you other functions, not the first only the first.

0
source

Source: https://habr.com/ru/post/1654428/


All Articles