2017-08-15 42 views
1

我試圖找到哪些函數在某些代碼中被使用。確定哪些函數在代碼中

  • 以爲他們會一直跟着開口支架
  • 循環正則表達式grepl("someFunction\\(", code)在函數名
  • 指定一定是有什麼比一個字母一樣,下劃線或點函數名的前面,因此frame未在data.frame(...)中找到。這是可能與以下正則表達式:grepl("[^a-zA-Z_\\.]someFunction\\(", code)
  • 在代碼開頭確保函數名仍然被前面加上空格代碼
  • 在函數名與\\.更換點發現:gsub(".","\\.",theFunctions, fixed=TRUE)

這裏的一個最小的可重複性測試:

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)) 

這似乎工作,但太長,不太可讀的人。
有沒有一種更優雅的方式來確定哪些功能出現在某些代碼中?

回答

2

您可以使用以下方法查找R代碼中使用的函數的名稱。功能get_functions可與代表字符串的代碼一起使用。

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))) 
    } 
    } 
} 

這裏,find_functions被遞歸調用,因爲表達式可以嵌套。

一個例子:

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" 

這種做法似乎是更安全的,因爲它使用的r解析器。此外,也可以找到沒有括號的函數(例如,:)。

相關問題