查找包含R函数定义的源文件 [英] Find the source file containing R function definition

查看:99
本文介绍了查找包含R函数定义的源文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自python背景,正试图与R保持同步,所以请多多包涵

I come from a python background and am trying to get up to speed with R, so please bear with me

我有一个R文件-util.R,其中包含以下几行:

I have an R file - util.R with the following lines:

util.add <- function(a,b) a + b
util.sub <- function(a,b) { a - b }

我的来源如下:

source('path/util.R')

我现在有两个函数对象,想要编写一个函数,如下所示:

I now have two function objects and want to write a function as follows:

getFilePath(util.add)

getFilePath(util.add)

那会给我这个结果

[1] "path/util.R"

推荐答案

如果您深入到足够的深度,那么进入已加载函数之一的srcref属性似乎可以正常工作.

Digging into the srcref attribute of one of the loaded functions appears to work, if you go deep enough ...

source("tmp/tmpsrc.R")
str(util.add)
## function (a, b)  
##  - attr(*, "srcref")=Class 'srcref'  atomic [1:8] 1 13 1 31 13 31 1 1
##   .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x8fffb18> 
srcfile <- attr(attr(util.add,"srcref"),"srcfile")
ls(srcfile)
## [1] "Enc"           "filename"      "fixedNewlines" "isFile"       
## [5] "lines"         "parseData"     "timestamp"     "wd"    
srcfile$filename
## [1] "tmp/tmpsrc.R"

这篇关于查找包含R函数定义的源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆