将函数调用转换为 R 中的字符

Ind*_*til 5 r function

我有一个更复杂的函数,但它的最小版本归结为以下我需要将用户输入的函数转换为字符的地方。但我不知道如何做到这一点(我也尝试了一堆rlang不起作用的黑客)。

foo <- function(.f) {
  if (as.character(.f) == "stats::lm") {
    print("this is lm")
  } else {
    print("this is not lm")
  }
}

foo(stats::lm)
#> Error in as.character(.f): cannot coerce type 'closure' to vector of type 'character'
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

use*_*1_G 4

也许这会起作用?

    deparse(substitute(stats::lm))
[1] "stats::lm"
Run Code Online (Sandbox Code Playgroud)

所以使用你的功能:

> foo <- function(.f) {
+   if (deparse(substitute(.f)) == "stats::lm") {
+     print("this is lm")
+   } else {
+     print("this is not lm")
+   }
+ }
> 
> foo(stats::lm)
[1] "this is lm"
Run Code Online (Sandbox Code Playgroud)