调用R脚本中的函数时如何获取R脚本文件名?
我有几个 R 脚本文件,例如 f1.R
、f2.R
、f3.R
。
我有另一个名为 AddSignal(signal) 的函数,它将信号向量添加到列表中。 f1.R、f2.R等中的函数可以调用此AddSignal()函数。
现在我想要的是,在函数 AddSignal() 中,除了执行添加信号部分之外,它还记录 R 文件中的哪个函数进行了调用。例如,我想知道 f1.R 中的函数 ff1() 添加了信号 sig1。
有办法做到这一点吗?
事实上,使用 sys.call(),我可以知道哪个函数(例如 ff1())调用了 AddSignal()。但我不知道 ff1() 位于哪个 R 文件中。我可以看到一种困难的方法,就是扫描所有 .R 文件,然后存储文件名和函数名的映射。但我想看看是否有更简单的方法。
谢谢。
I have several R script files, such as f1.R
, f2.R
, f3.R
.
I have another function called AddSignal(signal), which adds a signal vector to a list. Functions in f1.R, f2.R, etc. may call this AddSignal() function.
Now what I want is that, in function AddSignal(), besides doing the add signal part, it also records which function in which R file made the call. For example, I'd like to know function ff1() in f1.R added signal sig1.
Is there a way to do that?
In fact, using sys.call(), I can know which function (for example, ff1()) called AddSignal(). But I don't know which R file that ff1() is in. I can see a hard way of doing it, is to scan all .R files and then store a mapping of file names and function names. But I'd like to see whether there is an easier way of doing it.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我要做的是创建一个查找表,将函数映射到它所在的 .R 文件。每次添加、删除或移动函数时,您都必须重新创建此表,但我认为最好每次要查找函数的源文件时都重新生成表。因此,这是我对创建这样一个表的看法:
对于我自己的一个包,这会导致:
您可以使用查找表来使用从 sys.call 获取的函数名称来执行映射。
编辑:鉴于您对非函数代码的评论,此代码使用解析,它不会评估代码。它搜索 parse 的输出,并清除函数,并且不应评估任何不是函数的代码或返回代码。我还没有彻底测试过,你可以尝试一下。
What I would do is create a lookup table which maps a function to the
.R
file it is in. You have to recreate this table every time you add, remove, or move a function, but I think it would be preferable to regenerating the table every time you want to find the source file of a function. So here is my take on create such a table:For one of my own packages this leads to:
You can use the lookup table to performing the mapping using the function name obtained from
sys.call
.EDIT: In view of your comment on non-function code, this code uses parse, which does not evaluate the code. It searches through the output of parse, and weeds out the functions, and should not evaluate any code or return code that is not a function. I haven't tested it exhaustively, give it a try.
您可以将
AddSignal(signal)
修改为you could modify
AddSignal(signal)
to