微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否有 R 函数来查找所有子函数

如何解决是否有 R 函数来查找所有子函数

假设我有一个用这种表示法表示的函数 shell,或者字符串表示法“shell”。

@MrFlick 提供了一些代码来列出主函数的所有子函数(内部函数调用)。

Regular expression to find function calls in a function body

call.ignore <-c("[[","[","&","&&","|","||","==","!=","-","+","*","/","!",">","<",":")

find.funcs <- function(f,descend=FALSE) {
    if( is.function(f)) {
        return(find.funcs(body(f),descend=descend))
    } else if (is(f,"name") | is.atomic(f)) {
        return(character(0))
    }
    v <- list()
    if (is(f,"call") && !(deparse(f[[1]]) %in% call.ignore)) {
        v[[1]] <- deparse(f)
        if(!descend) return(v[[1]])
    } 
    v <- append(v,lapply(as.list(f),find.funcs,descend=descend))
    unname(do.call(c,v))
}

这个功能相当健壮。

find.functions(shell);  # works as expected
find.functions("shell"); # breaks

fn = "shell";
find.functions(fn); # breaks

如何扩展它以允许字符串表示法“shell”以便函数是可变参数的?

似乎可以根据 return(character(0)) 是否是字符串来更新它,但是通过递归,我没有让它按预期工作。

fstr = "shell";
f <- deparse(body(get(fstr)));

fstr = "shell";
f = eval(parse(text=fstr));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。