R函数可以访问自己的名字吗?

nsh*_*eff 3 r function

你能写一个打印出自己名字的功能吗?

(显然没有硬编码)

Jos*_*ich 7

你确定可以.

fun <- function(x, y, z) deparse(match.call()[[1]])
fun(1,2,3)
# [1] "fun"
Run Code Online (Sandbox Code Playgroud)


mds*_*ner 5

你可以,但是以防万一,因为你想以递归的方式调用函数,看看?Recall哪个对于命名更改是健壮的,并且避免了以其他方式处理获取名称的需要.

召回包:基础R文档

递归调用

描述:

‘Recall’ is used as a placeholder for the name of the function in
which it is called.  It allows the definition of recursive
functions which still work after being renamed, see example below.
Run Code Online (Sandbox Code Playgroud)


Tom*_*mmy 5

正如你在其他很好的答案中看到的那样,答案似乎是"是"......

但是,正确的答案实际上是"是的,但并非总是如此".你能得到的实际上是用于调用函数的名称(或表达式!).

首先,使用sys.call可能是查找名称的最直接方式,但是您需要将其强制转换为字符串.deparse对此更加强大.

myfunc <- function(x, y=42) deparse(sys.call()[[1]])

myfunc (3) # "myfunc"
Run Code Online (Sandbox Code Playgroud)

...但你可以通过多种方式调用函数:

lapply(1:2, myfunc) # "FUN"
Map(myfunc, 1:2) # (the whole function definition!)
x<-myfunc; x(3)   # "x"
get("myfunc")(3) # "get(\"myfunc\")"
Run Code Online (Sandbox Code Playgroud)

基本问题是函数没有名称 - 只是您通常将函数分配给变量名称.不是你必须 - 你可以有匿名函数 - 或者为同一个函数分配许多变量名(x上面的例子).