如何获取函数内使用的内置函数列表 [英] How to get the list of in-built functions used within a function
问题描述
可以说我有一个名为 Fun1
的函数,其中我使用了许多不同的R内置函数来处理不同的进程。那么我怎样才能得到这个函数中使用的内置函数列表 Fun1
Fun1 < - 函数(x,y){
sum(x,y)
mean(x,y)
c(x,y)
print x)
print(y)
}
所以我的输出应该是字符列表,即 sum
, mean ,
c
,打印
。因为这些是我在函数 Fun1
中使用的内置函数。
我试过使用 function
grep(\\(,body(Fun1) ,value = TRUE)
#[1]sum(x,y)mean(x,y)c(x,y)print(x)print(y)
它看起来不错,但参数不应该出现,例如 x
和 y
。 b
$ b
因此,我的总体目标是在特定函数内打印唯一列表的内置函数或任何创建函数,这里
Fun1
。
对此非常感谢。您可以使用 all.vars()
来获取所有出现在主体内部的变量名称(包括函数) Fun1
,然后将它与一些准备好的函数列表进行比较提到内置函数,所以我将它与基础包对象名进行比较。
##内部变量名的完整列表函数体
(vars < - all.vars(body(Fun1)[ - 1],functions = TRUE))
#[1]sumxymean cprint
##比较它与基本包对象名称
intersect(vars,ls(baseenv()))
#[1]sum meancprint
我删除了函数体的第一个元素,因为大概是你不关心 {
,它会与基本包列表匹配。
另一种可能性,尽管不太可靠,可能是将 Fun1
的形式参数与函数中的所有变量名进行比较。就像我说的那样,尽管可能不太可靠,因为如果你在函数内部进行赋值,结果会得到不正确的结果。
setdiff vars,names(formals(Fun1)))
#[1]summeancprint
这些都很有趣,你可以随意摆弄它们。
Lets say I have a function named Fun1
within which I am using many different in-built functions of R for different different processes. Then how can I get a list of in-built functions used inside this function Fun1
Fun1 <- function(x,y){
sum(x,y)
mean(x,y)
c(x,y)
print(x)
print(y)
}
So My output should be like list of characters i.e. sum
, mean
, c
, print
. Because these are the in-built functions I have used inside function Fun1
.
I have tried using grep
function
grep("\\(",body(Fun1),value=TRUE)
# [1] "sum(x, y)" "mean(x, y)" "c(x, y)" "print(x)" "print(y)"
It looks ok, but arguments should not come i.e. x
and y
. Just the list of function names used inside body of function Fun1
here.
So my overall goal is to print the unique list of in-built functions or any create functions inside a particular function
, here Fun1
.
Any help on this is highly appreciated. Thanks.
You could use all.vars()
to get all the variable names (including functions) that appear inside the body of Fun1
, then compare that with some prepared list of functions. You mention in-built functions, so I will compare it with the base package object names.
## full list of variable names inside the function body
(vars <- all.vars(body(Fun1)[-1], functions = TRUE))
# [1] "sum" "x" "y" "mean" "c" "print"
## compare it with the base package object names
intersect(vars, ls(baseenv()))
# [1] "sum" "mean" "c" "print"
I removed the first element of the function body because presumably you don't care about {
, which would have been matched against the base package list.
Another possibility, albeit a bit less reliable, would be to compare the formal arguments of Fun1
to all the variable names in the function. Like I said, likely less reliable though because if you make assignments inside the function you will end up with incorrect results.
setdiff(vars, names(formals(Fun1)))
# [1] "sum" "mean" "c" "print"
These are fun though, and you can fiddle around with them.
这篇关于如何获取函数内使用的内置函数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!