提问人:dykaplan 提问时间:9/3/2023 更新时间:9/3/2023 访问量:53
在不调用函数的情况下在 R 中声明所有函数参数
Declare All Function Parameters in R Without Calling the Function
问:
我想要一个函数,在该函数中,我抛出任何给定的其他函数,其中包含多个同时使用单引号和双引号的参数。
例如:
just_params("some_function(param1="this",param2='that')")
或
just_params(some_function(param1="this",param2='that'))
这导致函数不会被调用,而是在环境中声明了两个新的字符串变量 param1 和 param2。任何一种选择都有效,但我认为#1会更容易。
由于双引号和单引号的混合,直接将所有这些内容都放在字符串中是很困难的。我希望在调试其他人的代码时使用它,并假设他们随意使用双引号和单引号。
是的,我知道我可以复制和删除逗号,但有时我正在调试带有 20 个参数的函数调用(我知道也很畏缩),但事实就是这样,我不想每次都复制、粘贴和删除逗号。
答:
2赞
user2554330
9/3/2023
#1
这是一种方法:
just_params <- function(call) {
# Get the expression that was in the call without evaluating it.
call <- substitute(call)
# Expand all arguments to their full names. This needs the
# called function to exist and be visible to our caller.
call <- match.call(get(call[[1]], mode = "function",
envir = parent.frame()),
call)
# Change the name of the function to "list" to return the arguments
call[[1]] <- `list`
# Evaluate it in the parent frame
eval(call, envir = parent.frame())
}
some_function <- function(param1, param2, longname) {}
just_params(some_function(param1 = "this", param2 = 'that', long = 1 + 1))
#> $param1
#> [1] "this"
#>
#> $param2
#> [1] "that"
#>
#> $longname
#> [1] 2
创建于 2023-09-03 使用 reprex v2.0.2
笔记:
- 如果调用缩写了名称,您将看到全名(使用的示例而不是
long
longname
) - 如果调用使用了表达式,则将对其进行计算(使用但返回的示例。
1 + 1
2
- 不保留引号的类型。
评论
0赞
Elin
9/3/2023
这真的很整洁,但我认为一个限制是它只设置显式设置的参数,但如果我正在调试,我可能想要显式设置其他参数。
0赞
Elin
9/3/2023
我认为这有点像 xy 问题。
0赞
Elin
9/4/2023
我不是要你做任何事情,只是发表评论。
0赞
dykaplan
9/4/2023
我想我错过了一些东西。我运行了你的代码,现在我在我的全球环境中有了just_params和some_function,但仅此而已。当然,这些参数是由最终just_params调用返回的,但它们没有在我的全局环境中声明。我觉得您的解决方案user2554330很接近,但是同样,只有函数在我的全局中声明,而不是参数。
1赞
user2554330
9/4/2023
您可以对返回的列表执行任何操作。如果要在全局环境中分配给这些变量,只需使用类似 .你可以把那一行放到函数中,但我认为这是一个糟糕的设计:下周你可能想把它们分配到其他地方。for (n in names(thelist)) assign(n, thelist[[n]], envir = globalenv())
评论
debugonce
some_function
list2env(as.list(str2lang("some_function(param1='this',param2='that')"))[-1L], .GlobalEnv)
formals(the_function)
rlang