可靠地从文本文件中提取R函数的名称

时间:2015-01-03 13:09:46

标签: regex r

我想在我的R脚本中找到我经常使用的命名函数(忽略“+”,“$”和“[)之类的运算符。如何编写一个优雅可靠的正则函数,匹配函数的名称已经难倒了到目前为止,这是一个小例子和我笨拙的代码。我欢迎更清晰,更可靠,更全面的代码。

test1 <- "colnames(x) <- subset(df, max(y))" 
test2 <- "sat <- as.factor(gsub('International', 'Int'l', sat))"
test3 <- "score <- ifelse(str_detect(as.character(sat), 'Eval'), 'Importance', 'Rating')"
test <- c(test1, test2, test3)

测试对象包括八个函数(colnames,subset,max,as.factor,gsub,ifelse,str_detect,as.character),前两个函数两次。与它们匹配的迭代是:

(result <- unlist(strsplit(x = test, split = "\\(")))
 [1] "colnames"                               "x) <- subset"                          
 [3] "df, max"                                "y)"                                    
 [5] "sat <- as.factor"                       "gsub"                                  
 [7] "'International', 'Int'l', sat)))"       "score <- ifelse"                       
 [9] "str_detect"                             "as.character"                          
[11] "sat), 'Eval'), 'Importance', 'Rating')"

然后,一系列手工制作的gsubs清除了这个特定测试集的结果,但是这些手动步骤无疑会落在其他较少设计的字符串上(我在下面提供一个)。

(result <- gsub(" <- ", " ", gsub(".*\\)", "", gsub(".*,", "", perl = TRUE, result))))
 [1] "colnames"      " subset"       " max"          ""              "sat as.factor" "gsub"          ""             
 [8] "score ifelse"  "str_detect"    "as.character"

下面的对象test4包括lapply,function,setdiff,unlist,sapply和union等函数。它也有缩进,因此有内部间距。我把它包括在内,以便读者可以尝试更难的情况。

test4 <- "contig2 <- lapply(states, function(state) {
                             setdiff(unlist(sapply(contig[[state]], 
                                                   function(x) { contig[[x]]})), union(contig[[state]], state))"

(result <- unlist(strsplit(x = test4, split = "\\("))) 
(result <- gsub(" <- ", " ", gsub(".*\\)", "", gsub(".*,", "", perl = TRUE, result))))
顺便说一下,这个SO问题与提取整个函数以创建包有关。 A better way to extract functions from an R script?

首次回答后编辑

test.R <- c(test1, test2, test3) # I assume this was your first step, to create test.R
save(test.R,file = "test.R") # saved so that getParseData() could read it
library(dplyr)
tmp <- getParseData(parse("test.R", keep.source=TRUE))
tmp %>% filter(token=="SYMBOL") # token variable had only "SYMBOL" and "expr" so I shortened "SYMBOL_FUNCTION_CALL"
  line1 col1 line2 col2 id parent  token terminal text
1     1    1     1    4  1      3 SYMBOL     TRUE RDX2
2     2    1     2    1  6      8 SYMBOL     TRUE    X

所有文字都发生了一些事情。我该怎么办?

2 个答案:

答案 0 :(得分:5)

正则表达式可能有效,但您可以使用R本身来帮助您。我将您的四行放入文件test.R,修复了语法问题&amp;运行以下内容:

library(dplyr)

tmp <- getParseData(parse("test.R", keep.source=TRUE))

tmp %>% filter(token=="SYMBOL_FUNCTION_CALL")

##   line1 col1 line2 col2  id parent                token terminal         text
## 1      1    1     1    8   1      3 SYMBOL_FUNCTION_CALL     TRUE     colnames
## 2      1   16     1   21  11     13 SYMBOL_FUNCTION_CALL     TRUE       subset
## 3      1   27     1   29  19     21 SYMBOL_FUNCTION_CALL     TRUE          max
## 4      2    8     2   16  39     41 SYMBOL_FUNCTION_CALL     TRUE    as.factor
## 5      2   18     2   21  42     44 SYMBOL_FUNCTION_CALL     TRUE         gsub
## 6      3   10     3   15  72     74 SYMBOL_FUNCTION_CALL     TRUE       ifelse
## 7      3   17     3   26  75     77 SYMBOL_FUNCTION_CALL     TRUE   str_detect
## 8      3   28     3   39  78     80 SYMBOL_FUNCTION_CALL     TRUE as.character
## 9      5   12     5   17 119    121 SYMBOL_FUNCTION_CALL     TRUE       lapply
## 10     6    3     6    9 134    136 SYMBOL_FUNCTION_CALL     TRUE      setdiff
## 11     6   11     6   16 137    139 SYMBOL_FUNCTION_CALL     TRUE       unlist
## 12     6   18     6   23 140    142 SYMBOL_FUNCTION_CALL     TRUE       sapply
## 13     8   11     8   15 191    193 SYMBOL_FUNCTION_CALL     TRUE        union

如您所见,text列包含您调用的函数的名称。这应该适用于所有语法正确的R文件。

请注意,它不会对代码进行解析,只需解析它。

编辑 test.R如下所示:

colnames(x) <- subset(df, max(y))
sat <- as.factor(gsub('International', 'Int\'l', sat))
score <- ifelse(str_detect(as.character(sat), 'Eval'), 'Importance', 'Rating')

contig2 <- lapply(states, function(state) {
  setdiff(unlist(sapply(contig[[state]],
                        function(x) { contig[[x]]})),
          union(contig[[state]], state))})

答案 1 :(得分:4)

问题中的代码没有有效的语法,但如果我们更正它:

test1 <- "colnames(x) <- subset(df, max(y))" 
test2 <- "sat <- as.factor(gsub('International', 'Intl', sat))"
test3 <- "score <- ifelse(str_detect(as.character(sat), 'Eval'), 'Importance', 'Rating')"
test <- c(test1, test2, test3)

然后我们可以在codetools包中使用findGlobals

library(codetools)

f.text <- c("function(){", test, "}")
f <- eval(parse(text = f.text))
funs <- findGlobals(f, merge = FALSE)$functions

,并提供:

 > funs
 [1] "{"            "<-"           "as.character" "as.factor"    "colnames<-"  
 [6] "gsub"         "ifelse"       "max"          "str_detect"   "subset"    

不清楚您希望排除哪些功能,但如果F是包含它们的字符向量,则setdiff(funs, F)将提供除此之外的所有功能。

另见Finding out which functions are called within a given function和:Generating a Call Graph in R