【发布时间】:2015-03-01 13:19:24
【问题描述】:
我想找到我在 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')"
然后,一系列手工制作的 gsub 会从这个特定的测试集中清除结果,但这些手动步骤无疑会在其他不那么做作的字符串上有所不足(我在下面提供了一个)。
(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
所有文本都发生了一些事情。我应该怎么做?
【问题讨论】: